# How to use sizeof operator to calculate number of elements in array of structures ?

`````` ParameterDef const  Parameters : : Info[ ] =
{
{ParameterId_Vendor,                                           0,       2,       0,  false,  null},
{ParameterId_SystemOverview,                          1,       2,       1,  false,  null},
.....
``````

We have large array of structures.  In our code, sizeof operator is used to find number of elements in the array as follows:

sizeof (Parameters : : Info) / sizeof ( * Parameters : : Info )

* Parameters : : Info    // is this the size of first element of the array ?

Would the following be equivalent:

sizeof (Parameters : : Info) / sizeof ( Parameters : : Info [ 0 ] )
LVL 1
###### Who is Participating?

Commented:
Hi naseeam,

yes, they're identical. A C-style array is nothing else than a pointer to the first element, accessing elements via [ ] is just doing some pointer arithmetics, so if you have an array called buf the statements buf[n] and *(buf+n) are the same, so *buf is the same as buf[0]

Hope that helps,

ZOPPO
0

Commented:
Yes, that would be one valid option - I'd prefer

``````#define countof(x) ((sizeof(x) / sizeof(*(x))))
``````

to be on the safe side syntactically and keep it more general.
0

Commented:
BTW, just as an addition because IMO it's courious and funny: Due to the fact [ ] is just compiled using pointer arithmetic you can even swap the pointer and the index, i.e. buf[n] is equal to n[buf] - looks strange but is correct.
0

Author Commented:
concise and useful macro to find number of elements in an array.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.