|
-
November 7th, 2002, 07:55 AM
#1
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
-
November 7th, 2002, 09:41 AM
#2
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
-
November 14th, 2002, 02:46 PM
#3
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).
-
November 15th, 2002, 10:28 AM
#4
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;
}
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|