Suslik
Suslik

Reputation: 1071

Convert Pointer to Pointer to a multi-dimensional array

Is it possible to convert a one dimensional const int *const p pointer of dimension ABC to a pointer to a multi-dimensional array of size [A][B][C]?

Upvotes: 0

Views: 170

Answers (2)

einpoklum
einpoklum

Reputation: 131515

Usually, it's not possible.

In the first case (an int[A][B][C] multi-dimensional array), all of your data is laid out contiguously in memory, and p[10][20][30] simply means *(p + B * C * 10 + B * 20 + 30). But the pointer is targeted at an array of pointers; and each of those points to another array of pointers; and only those second arrays point to the data. The data and the second-level pointer-arrays may not be consecutive. So you can certainly not take the address of the first element of data and use an offset to get to what you're looking for.

The exception is the case where someone does take care to place all of the data contiguously, with the pointer arrays pointing into it at appropriate positions. In that case you can take &( *(*(*multidim_ptr))), i.e. &( *(*multidim_ptr)), as your one-dimension pointer which can be used like p.

Upvotes: 2

Gardener
Gardener

Reputation: 2660

Here is an example of how to do this. The key is using a typedef to setup your pointer to the array of pointers so that you don't get too confused.

typedef int (*pint3)[A][B];

In this line, we set up a type that points to a two-dimensional array of pointers to int. The 2D array has dimensions equal to two of the dimensions that you originally were considering.

As mentioned in the comments, this method violates aliasing. This type of pointer reassignment is error-prone and should probably be avoided.

#include <iostream>

int main() {

    int A = 2;
    int B = 2;
    int C = 3;

    int array[]{1, 1, 1, 1, 2, 2, 2,2, 3,3,3,3};



    const int *const p = array;

    typedef int (*pint3)[A][B];

    auto threeDArray = (pint3) p;

    std::cout << "Printing 3D array:  " << std::endl;
    for(int i = 0; i < C; i++ ) {
        for(int j = 0; j < B; j++) {
            for (int k = 0; k < A; k++) {
                std::cout << threeDArray[i][j][k];
            }
            std::cout << std::endl;
        }
        std::cout << std::endl;

    }
}

Output:

Printing array:  
11
11

22
22

33
33


Process finished with exit code 0

Upvotes: 3

Related Questions