Monday, March 22, 2010

Cool little sizeof tricks

Here are a few little tricks for sizeof arrays.

Firstly, the sizeof operator typically returns the sizeof an array in bytes. Let's say that we have the following snippet:

int    array[20];
int x = sizeof (array);

// x = 80


Working from there, we can easily find out the number of items in an array.


#define ArraySize(a) sizeof(a)/sizeof(a[0])

int num = ArraySize(array);

// num = 10


Lastly, what do you do if you need the number of elements in an array that is a member variable of a struct or class? Here we need an instance of a variable to access its member variables so we declare a pointer to 0 and access its array member. Normally, this might produce strange results, but during compile-time, this works fine.

struct dummy
{
    int array[10];
};

#define MemberArraySize(a,array) (sizeof(((a*)(0))->array)) / (sizeof(((a*)(0))->array[0]))
int num = MemberArraySize(dummy, array);

// num = 10

No comments: