Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array element count in C

I've always used following paradigm for iterating over statically-defined arrays in C:

struct foo { ... };
struct foo array[10];

for (int i; i < sizeof(array) / sizeof(array[0]); i++)
    ...

And, well, this worked every time so far ;-)

But it makes wonder, could this not break if the struct was actually of length that doesn't align naturally, e.g.:

struct foo { long a; char b; };

Shouldn't the compiler decide that sizeof(struct foo) == 7 while sizeof(array) == 32 due to alignment (LP64 data model)?

like image 882
Dima Tisnek Avatar asked Jan 14 '16 14:01

Dima Tisnek


2 Answers

As the C99 standard, section 6.5.3.4 states about sizeof operator:

When applied to an operand that has array type, the result is the total number of bytes in the array.

And:

EXAMPLE 2 Another use of the sizeof operator is to compute the number of elements in an array:

     `sizeof array / sizeof array[0]`

So the size of array will always be a multiple of size of it's elements.

And from the same paragraph about structs:

When applied to an operand that has structure or union type, the result is the total number of bytes in such an object, including internal and trailing padding.

like image 150
Eugene Sh. Avatar answered Sep 27 '22 22:09

Eugene Sh.


No.

There is no "dead space" in an array; if there's padding, it's included in the struct size.

like image 43
unwind Avatar answered Sep 27 '22 22:09

unwind