Why can't I convert a two-dimensional array to

2020-02-11 09:28发布

问题:

Why does the following program give a 'conversion' : cannot convert from int[1][1] to int** error? I am compiling with VS2008 under Windows 7.

int main(){
    int a[1][1] = {0};
    int **p = a;
}

回答1:

You can only convert arrays to pointers one time. The "pointers == arrays" abstraction breaks from the second level onwards.

You can do

int (*p)[1] = a; //convert an array of arrays of length 1
                 // to a pointer to arrays of length 1

But it becomes clear you cannot convert multidimentional arrays to pointers-to-pointers if you see the memory layout in each case:

//multidimentional arrays (a[][])
a -> [first row][second row][...]

//pointers to pointers (**p)
p -> [p0][p1][p2]
      |    |   |
      |    |   \-> [third row]
      |    \-----> [second row]
      \----------> [first row]

In the pointer-to-pointer approach the rows are not necessarily contiguous and there needs to be an extra array for the spine that points to the individual rows.



回答2:

a is an array of an array of ints, so it can decay to a pointer to the first element, which is an array of ints. So you need to declare the pointer as follows:

int (*p)[1] = a;

More abstractly, if you have an array T a[N];, then a decays to a T*. In your situation, you have T = int[M], and so T* = int(*)[M].