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?
CodePudding user response:
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.
CodePudding user response:
Yes, but...
First of all, as std::array
is just a tiny wrapper around a plain array, both simple_2D_array
and std_2D_array
will have exactly the same memory layout.
Next, that memory layout would be the same as the one of a 1D array of size 20 but there will be a strong difference between the 1D array and any of the 2D ones
- for the 1D array, the declared size of the array is the total size of the object: it is legal to use for example
arr[6]
. - for the 2D objects, the declared size of any integer array is only 4. On a strict language point of view, as pointer arithmetics is only define inside an array it is illegal (thus Undefined Behaviour) to browse the whole array as if it was a 1D array of size 20.
Of course, any common compiler will accept that and produce the expected output because it used to be a common idiom and rejecting it would break a lot of legacy code. Yet it is not valid C (I have no reference at the moment, but it has been discussed on SO...)