Click to See Complete Forum and Search --> : getting size of an element in 2-dimensional array


aninddroy
November 7th, 2002, 06:55 AM
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

ZuK
November 7th, 2002, 08:41 AM
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

KevinHall
November 14th, 2002, 01:46 PM
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).

Axter
November 15th, 2002, 09:28 AM
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;
}