CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 4 of 4
  1. #1
    Join Date
    Nov 2002
    Location
    India
    Posts
    3

    Question getting size of an element in 2-dimensional array

    Hi,
    How do u get the size of a particular element in a 2-dimensional array ?? Can u use 'sizeof' operator as in other cases ??
    like this,
    size_t ElementSize = sizeof(arr[2][3]);

    Can we do it this way ??

    Please let me know.

    Regards,
    Anind

  2. #2
    Join Date
    Oct 2002
    Location
    Austria
    Posts
    1,284
    Yes that works.
    But all elements in a multidimensional array have the same size so why not do something like ..

    int arr[5][5];
    size_t ElementSize = sizeof( int );

    Kurt

  3. #3
    Join Date
    Nov 2002
    Location
    Foggy California
    Posts
    1,245
    You can also get the size of an element by:

    sizeof(arr[0][0])

    FYI, a particularly useful macro is this:

    #define ARRAY_SIZE(x) (sizeof(x)/sizeof((x)[0]))

    This will return the number of elements in a one dimensional array. For a two dimensional array it will return the size of the second dimension (or the number of 1-dimensional arrays).

  4. #4
    Join Date
    Aug 2000
    Location
    New Jersey
    Posts
    968
    For a more C++ approach, you can use the following template functions to get the size.


    template<typename T>
    int QtyInFirst(T& t)
    {
    return (sizeof(t)/sizeof((t)[0]));

    }

    template<typename T>
    int QtyInSecond(T& t)
    {
    return (sizeof(t[0])/sizeof((t)[0][0]));

    }

    template<typename T>
    int SizeOfBase(T& t)
    {
    return sizeof(t[0][0]);
    }

    Example usuage:

    int main(int, char**)
    {
    int xx1[2][44] = {3};
    int xx2[5][33] = {4};
    int a1 = QtyInFirst(xx1);
    int a2 = QtyInFirst(xx2);
    int b1 = QtyInSecond(xx1);
    int b2 = QtyInSecond(xx2);
    int e1 = SizeOfBase(xx1);
    int e2 = SizeOfBase(xx2);
    return 0;
    }
    David Maisonave
    Author of Policy Based Synchronized Smart Pointer
    http://axter.com/smartptr


    Top ten member of C++ Expert Exchange.
    C++ Topic Area

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured