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}, 

Open in new window

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 ] )
Who is Participating?
ZoppoConnect With a Mentor 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,

jkrConnect With a Mentor Commented:
Yes, that would be one valid option - I'd prefer

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

Open in new window

to be on the safe side syntactically and keep it more general.
ZoppoConnect With a Mentor 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.
naseeamAuthor Commented:
concise and useful macro to find number of elements in an array.
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.

All Courses

From novice to tech pro — start learning today.