Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is this sizeof trick doing?

Tags:

c

sizeof

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

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

Then later they use this as part of a for loop:

sizeof(trysizes)/sizeof*(trysizes)

I'm thinking the first part is the number of bytes in the array and the second part must be the size of each array member giving us the number of items in the array. Is this a standard way to calculate array length and what is the second sizeof actually doing?

like image 564
Ben Flynn Avatar asked Jul 27 '12 21:07

Ben Flynn


1 Answers

Yes, after fixing the confusing syntax so this becomes

sizeof(trysizes)/sizeof(*trysizes)

or even better

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

this is the preferred way of computing the number of elements of an array. The second sizeof indeed computes the size of element 0 of the array.

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

like image 91
Fred Foo Avatar answered Sep 30 '22 15:09

Fred Foo