Display Name
Display Name

Reputation: 15111

How to construct an auxiliary array for casting "int[][][]" to "int***"?

I am a newbie in C++ and it is only for learning purposes.

I just understood how to cast int input [][] to int** output with an auxiliary int* aux [] as follows.

int TwoD()
{
    int input[][3] = { {1,2,3},{4,5,6} };

    int* aux[2];

    aux[0] = input[0];// array of int ---> pointer to int
    aux[1] = input[1];// array of int ---> pointer to int

    int** output = aux;// array of int* ---> pointer to int*

    for (int i = 0; i < 2; i++)
        for (int j = 0; j < 3; j++)
            cout << output[i][j] << endl;
}

Now I want to extend it to 3D as follows.

void ThreeD()
{
    int input[2][3][4] =
    {
        {
            {1,2,3,4},
            {5,6,7,8},
            {9,10,11,12}
        },
        {
            {13,14,15,16},
            {17,18,19,20},
            {21,22,23,24}
        }
    };

    //int(*output)[3][4] = input;

    int** aux[2];
    aux[0][0] = input[0][0];
    aux[0][1] = input[0][1];
    aux[0][2] = input[0][2];
    aux[1][0] = input[1][0];
    aux[1][1] = input[1][1];
    aux[1][2] = input[1][2];

    int*** output = aux;

    for (int i = 0; i < 2; i++)
    {
        for (int j = 0; j < 3; j++)
        {
            for (int k = 0; k < 4; k++)
                cout << output[i][j][k] << " ";
            cout << endl;
        }
        cout << endl;
    }
}

It compiles but only produce a blank screen. What is the correct auxiliary aux and how to initialize it?

Upvotes: 1

Views: 457

Answers (1)

R Sahu
R Sahu

Reputation: 206667

You need another layer of pointers.

int input[2][3][4] =
{
   {
      {1,2,3,4},
      {5,6,7,8},
      {9,10,11,12}
   },
   {
      {13,14,15,16},
      {17,18,19,20},
      {21,22,23,24}
   }
};

int* aux1[2][3] =
{
   { input[0][0], input[0][1], input[0][2] },
   { input[1][0], input[1][1], input[1][2] },
};

int** aux2[2] = {aux1[0], aux1[1]};

int*** output = aux2;

Upvotes: 2

Related Questions