Suppose I have some type T
that has to be N
bytes aligned. Now I declare an array of type T
:
T array[size];
Will the array have the same alignment requirements as type T
or will it have any other alignment requirements?
By default, the compiler aligns class and struct members on their size value: bool and char on 1-byte boundaries, short on 2-byte boundaries, int , long , and float on 4-byte boundaries, and long long , double , and long double on 8-byte boundaries.
Yes, the alignment requirements must be the same. Obviously an array of T
must be aligned at least as strictly as a single T
otherwise its first member would not be properly aligned. The fact that an array cannot be more strictly aligned than its element type follows from the standard section 8.3.4 which says that arrays are contiguously allocated element subobjects. Consider this array of arrays:
T a[2][size];
Whatever the value of size
, there can be no "extra" padding between the two arrays a[0]
and a[1]
otherwise this violates the contiguosly allocated requirement.
Equivalently, we know that (char*)&a[1] == (char*)&a[0] + sizeof(a[0])
and sizeof(a[0]) == sizeof(T[size]) == size * sizeof(T)
. As this holds for any size
it must be possible to place an array of T
at any address which is suitably aligned for a single T
object (given adequate address space).
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