What will be the memory layout when defining multidimensional std array?
will it be single continuous memory block or array of pointer?
for example –
const size_t M = 5;
const size_t N = 4;
int simple_2D_array[M][N];
std::array<std::array<int,N>,M> std_2D_array;
is it guarantee that both simple_2D_array and std_2D_array will have the same memory layout as single continuous memory?
>Solution :
int simple_2D_array[M][N];
This is guaranteed to be contiguous in memory. You can use pointer arithmetic to calculate the position of any index relative to the start.
std::array<std::array<int,N>,M> std_2D_array;
This, in general, does not have to be contiguous in memory. It is an array of objects, each of which happens to be an array. While each of the internal arrays is logically equivalent to a C-style array as its only non-static data member, it is permissible for the compiler to decide that the entire internal array requires padding.
So, in practice, it is probably contiguous, but it probably doesn’t pay to rely on that. Just write an iterator or something.