What is this trick of this size?

It's been a while since I looked at the C code, but I'm trying to figure out what is going on here. Someone declared this (has more members in their code):

int trysizes[] = { 64, 64, 128, 64, }; 

Then they use this as part of the for loop:

 sizeof(trysizes)/sizeof*(trysizes) 

I think the first part is the number of bytes in the array, and the second part is the size of each member of the array, which gives us the number of elements in the array. Is this the standard way to calculate the length of an array and what the second size actually does?

+8
c sizeof
source share
3 answers

Yes, after correcting the confusing syntax to make it become

 sizeof(trysizes)/sizeof(*trysizes) 

or even better

 sizeof(trysizes)/sizeof(trysizes[0]) 

this is the preferred way to calculate the number of elements in an array. The second sizeof really calculates the size of element 0 array.

Note that this only works when trysizes is actually an array, not a pointer to one.

+15
source share

Did you understand. The second sizeof in the denominator cancels references to the first element of the array, which gives the element size 0 . sizeof knows the total buffer size of the array variable — the numerator — and therefore this idiom will give the number of elements in the array.

In my experience, this is an unusual expression of this particular idiom, as a rule, I have seen, and I use:

 sizeof(var)/sizeof(var[0]); 

This more clearly identifies the variable as an array, not a pointer.

This is a fairly common trick, but keep in mind that it only works if the variable is declared as an array, for example. this will not work on an array that has been converted to a pointer as a function parameter.

+1
source share

Keypiont is that when using sizeof, although we mostly use int a; sizeof(a); int a; sizeof(a); , we can also omit parentheses, for example: int a; sizeof a; int a; sizeof a;
So, in this case, sizeof*(trysizes) == sizeof *trysizes == sizeof(*trysizes)

+1
source share

All Articles