为什么我不能将二维数组转换为C中的二维指针?
为什么以下程序给出'conversion' : cannot convert from int[1][1] to int**
错误? 我在Windows 7下使用VS2008进行编译。
int main(){ int a[1][1] = {0}; int **p = a; }
您只能将数组转换为指针一次。 “指针==数组”抽象从第二级开始打破。
你可以做
int (*p)[1] = a; //convert an array of arrays of length 1 // to a pointer to arrays of length 1
但很明显,如果在每种情况下都看到内存布局,则无法将多维数组转换为指针指针:
//multidimentional arrays (a[][]) a -> [first row][second row][...] //pointers to pointers (**p) p -> [p0][p1][p2] | | | | | \-> [third row] | \-----> [second row] \----------> [first row]
在指向指针的方法中,行不一定是连续的,并且脊柱需要有一个指向各行的额外数组。
a
是一个int
数组的数组,因此它可以衰减到指向第一个元素的指针,该元素是一个int
数组。 所以你需要声明指针如下:
int (*p)[1] = a;
更抽象的是,如果你有一个数组T a[N];
,然后衰变到T*
。 在你的情况下,你有T = int[M]
,所以T* = int(*)[M]
。