Is this C++ code portable? (assuming multidimensional arrays have continuous memory layout)

arrays, c++, memory, multidimensional-array, portability

Solution

Standardese

The elements of the multidimensional array are stored sequentially in row-major order, so the manual indexing is portable:

C++98, 8.3.4/1:

An object of array type contains a contiguously allocated non-empty set of N sub-objects of type T.

Obviously for a multidimensional array this applies recursively.

However, this use of `reinterpret_cast` is not portable. The standard says (C++98, 5.2.10/1) that

[...] otherwise, the result is an rvalue and the [...], array-to-pointer, [...] standard conversions are performed on the expression v.

In other words, passing `arr` immediately triggers a decay of the array to a pointer to its first element. Then (C++98, 5.2.10/3) comes the catch-all

The mapping performed by `reinterpret_cast` is implementation-defined.

The rest of the section lists a number of exceptions to this, specifying casts that are always well-defined. Seeing as none of them applies here, the conclusion is that technically it's implementation-defined by default.

Final conclusion

Theoretically speaking, this is not portable. Practically, as long as the architectures are the same (e.g. x86) I would certainly expect the cast to work reliably.

Fortunately you don't have to assume anything like that because as others have mentioned, something like `int* ptr = arr[0]` does the same thing and is guaranteed portable.

Problem

First of all, sorry for my english if i make any grammar mistakes, etc ... My question is, that when we have a two dimensional array, then if i am right, from the point of the computer and C/C++, it's just a long one dimensional array, the indices are just helping the compiler to map to the concrete address. This code fragment works in Visual C++, however I would like to know, whether this code is portable and conforms to the standard (C++98), not causing surprises on other architectures and/or operating systems: ``` int arr[][3] = { 1, 5, 3, 7, 5, 2, 7, 8, 9 }; const int ARR_NUM = sizeof(arr) / sizeof(int); int* ptr = reinterpret_cast<int*>(arr); // NOT: int(*)[][3] !!! for (int i = 0; i < ARR_NUM; ++i) { cout << ptr[i] << endl; } ```

Original source