Home > Article > Backend Development > Does the C Standard Guarantee the Same Size and Memory Layout for `std::array` as for Built-in Arrays?
Does C Standard Define the Size of std::array?
In C 11, std::array offers contiguous storage with performance comparable to regular arrays. However, it's unclear if std::array's size and memory layout mirror that of normal arrays.
Standard Requirements
The C standard (§23.3.2.1/2) defines an array as an aggregate initialized via:
array<T, N> a = { initializer-list };
As an aggregate, std::array cannot use constructors to convert data in the initializer-list. This implies that it primarily stores the actual data values.
Potential Implementation-Specific Behavior
Technically, it's possible for an std::array to include auxiliary data or non-standard alignment, which would deviate from a normal array's behavior.
For instance, a compiler could add a sentinel value at the end of an std::array to detect out-of-bounds write attempts. Alternatively, super-alignment (e.g., Intel SSE instructions) could be supported by an std::array but not by a built-in array.
Expected Behavior
In general, you can expect the following code to behave as intended:
std::vector< std::array<int, N> > x(M); typedef int (*ArrayPointer)[N]; ArrayPointer y = (ArrayPointer) &x[0][0]; // Use y as a multidimensional array
Most compilers (e.g., GNU and Intel) adhere to this behavior. However, it's important to note that the standard does not explicitly guarantee identical memory layout for std::array and normal arrays.
The above is the detailed content of Does the C Standard Guarantee the Same Size and Memory Layout for `std::array` as for Built-in Arrays?. For more information, please follow other related articles on the PHP Chinese website!