Assigning a 2d array pointer parameter to a local array pointer variable

Viewed 76

I am a little bit confused about how to assign a 2d array pointer parameter to a local 2d array pointer variable. Check the code below.

#define N   5
#define M   6

void print(int (*arr)[M][N]) {

    int *localArr[M][N];

    localArr = arr;  //error C3863: array type 'int *[6][5]' is not assignable
    //localArr[0][0] =1; and so on.
}

int main()
{

    int Array1[M][N];
    print(&Array1);         
}
3 Answers

the local declaration has to be like this way,

 int (*localArr)[M][N]; //pointer to an MxN array
 //int * localArr[m][N];//An MxN array of pointer to int

What do you want to achieve? If you just want to print your 2d array then why don't you use this approach?

void print(int localArr[M][N]) {

    for (int i = 0; i < M; i++) {
        for (int j = 0; j < N; j++) {
            cout << localArr[i][j];
        }
    }
}

If there are some constraints then Nitheesh is right!

If we change the sizes to make it easier to fit:

#define M 2
#define N 3

Then somewhat graphically the variable arr is something like this:

+-----+      +--------+--------+--------+--------+--------+--------+
| arr | ---> | [0][0] | [0][1] | [0][2] | [1][0] | [1][1] | [1][2] |
+-----+      +--------+--------+--------+--------+--------+--------+

arr is a pointer. It points to an array of arrays, where each element is an int.

That means you can dereference arr to get what it points to, and then use array indexing on that to get an int value:

int value = (*arr)[0][1];

Now if we take localArr instead, it's more like

+----------------+----------------+----------------+----------------+----------------+----------------+
| localArr[0][0] | localArr[0][1] | localArr[0][2] | localArr[1][0] | localArr[1][1] | localArr[1][2] |
+----------------+----------------+----------------+----------------+----------------+----------------+

localArr is an array of arrays, where each element is a int *.

So you need an int * to get a single element:

int *pointer = localArr[0][1];
Related