Search code examples
c++arrayspointersmultidimensional-arraysyntax

Given a 2D array int[][], what does it mean to create a pointer int(*)[]?


I have a question about a pointer to 2d array. If an array is something like

int a[2][3];

then, is this a pointer to array a?

int (*p)[3] = a;

If this is correct, I am wondering what does [3] mean from int(*p)[3]?


Solution

  • Rather than referring to int[2][3] as a '2d array', you should consider it to be an 'array of arrays'. It is an array with two items in it, where each item is itself an array with 3 ints in it.

    int (*p)[3] = a;
    

    You can use p to point to either of the two items in a. p points to a three-int array--namely, the first such item. p+1 would point to the second three-int array. To initialize p to point to the second element, use:

    int (*p)[3] = &(a[1]);
    

    The following are equivalent ways to point to the first of the two items.

    int (*p)[3] = a; // as before
    int (*p)[3] = &(a[0]);