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)?
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.
No.
There is no "dead space" in an array; if there's padding, it's included in the struct
size.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With