I heard a rumor that, in C, arrays that are contained inside structs may have padding added in between elements of the array. Now obviously, the amount of padding could not vary between any pair of elements or calculating the next element in an array is not possible with simple pointer arithmetic.
This rumor also stated that arrays which are not contained in structures are guaranteed to contain no padding. I know at least that part is true.
So, in code, the rumor is:
{ // Given this: struct { int values[20]; } foo; int values[20]; // This may be true: sizeof(values) != sizeof(foo.values); }
I'm pretty certain that sizeof(values)
will always equal sizeof(foo.values)
. However, I have not been able to find anything in the C standard (specifically C99) that explicitly confirms or denies this.
Does anyone know if this rumor is addressed in any C standard?
edit: I understand that there may be padding between the end of the array foo.values
and the end of the struct foo
and that the standard states that there will be no padding between the start of foo
and the start of foo.values
. However, does anyone have a quote from or reference to the standard where it says there is no padding between the elements of foo.values
?
As each 'member' of an array has the same alignment requirement, there's no reason to introduce padding. This holds true for arrays contained in structures as well: If an array's first elment is correctly aligned, so are all following elements.
Arrays of Structs always contain Objects of the same Type. So by adding a Padding at the end to make the total size a multiple of the biggest Member's size we can be certain all other Structs following will be aligned just like the first of the sequence is.
Dimensions used when declaring arrays in C must be positive integral constants or constant expressions. In C99, dimensions must still be positive integers, but variables can be used, so long as the variable has a positive value at the time the array is declared.
Initialize Arrays in C/C++The array will be initialized to 0 if we provide the empty initializer list or just specify 0 in the initializer list. d. If the calloc() function is used, it will allocate and initialize the array with 0.
No, there will never be padding in between elements of an array. That is specifically not allowed. The C99 standard calls array types "An array type describes a contiguously allocated nonempty set of objects...". For contrast, a structure is "sequentially", not "contiguously" allocated.
There might be padding before or after an array within a structure; that is another animal entirely. The compiler might do that to aid alignment of the structure, but the C standard doesn't say anything about that.
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