Treating 2D array as 1D array

  • A+

Let's say we have a 2D int array:

int a[3][4] = { { 1,3,2,4 }, { 2,1,5,3 }, { 0,8,2,3 } }; 

Is it legal and valid to take its address and reinterpret it as a pointer to 1D array of ints? Basically:

int *p = reinterpret_cast<int *>(&a); 

So that I can do things like (roughly):

template<typename T, size_t X, size_t Y> void sort2(T(&arr)[X][Y]) {     T *p = reinterpret_cast<T *>(&arr);     std::sort(p, p + X*Y); } 


To my knowledge, the standard guarantees that alignment of 2D array would be contiguous in memory, and although p + X*Y technically is out of range is never accessed so should not lead to Undefined Behaviour either.

Can I absolutely treat 2D arrays as 1D arrays when needed?


Yes. It is legal and valid.

As per dcl.array:

If E is an n-dimensional array of rank i×j×⋯×k , then E appearing in an expression that is subject to the array-to-pointer conversion is converted to a pointer to an (n−1)-dimensional array with rank j×⋯×k. If the * operator, either explicitly or implicitly as a result of subscripting, is applied to this pointer, the result is the pointed-to (n−1)-dimensional array, which itself is immediately converted into a pointer.


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: