Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How is an array aligned in C++ compared to a type contained?

Tags:

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?

like image 304
sharptooth Avatar asked Nov 08 '12 07:11

sharptooth


People also ask

What is the default alignment in C++?

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.


1 Answers

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).

like image 84
CB Bailey Avatar answered Oct 15 '22 04:10

CB Bailey