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 ] )
LVL 1
naseeamAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

ZoppoCommented:
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

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
jkrCommented:
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.
0
ZoppoCommented:
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
naseeamAuthor Commented:
concise and useful macro to find number of elements in an array.
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
C++

From novice to tech pro — start learning today.