我试图将两个固定大小的数组分配给指向它们的指针数组,但是编译器警告我,我不明白为什么.
I tried to assign two fixed-size arrays to an array of pointers to them, but the compiler warns me and I don't understand why.
int A[5][5]; int B[5][5]; int*** C = {&A, &B};此代码编译时显示以下警告:
This code compiles with the following warning:
警告:从不兼容的指针类型初始化(默认情况下启用)
warning: initialization from incompatible pointer type [enabled by default]
如果我运行代码,它将引发分段错误.但是,如果我动态分配A和B,它就可以正常工作. 这是为什么?
If I run the code, it will raise a segmentation fault. However, if I dynamically allocate A and B, it works just fine. Why is this?
推荐答案如果您想要一个符合现有A和B声明的C声明,则需要这样做:
If you want a declaration of C that fits the existing declarations of A and B you need to do it like this:
int A[5][5]; int B[5][5]; int (*C[])[5][5] = {&A, &B};C的类型读取为" C是指向int [5][5]数组的指针的数组".由于无法分配整个数组,因此需要分配一个指向该数组的指针.
The type of C is read as "C is an array of pointers to int [5][5] arrays". Since you can't assign an entire array, you need to assign a pointer to the array.
使用此声明,(*C[0])[1][2]正在访问与A[1][2]相同的内存位置.
With this declaration, (*C[0])[1][2] is accessing the same memory location as A[1][2].
如果您想要更简洁的语法,例如C[0][1][2],则需要执行其他人所说的并动态分配内存:
If you want cleaner syntax like C[0][1][2], then you would need to do what others have stated and allocate the memory dynamically:
int **A; int **B; // allocate memory for A and each A[i] // allocate memory for B and each B[i] int **C[] = {A, B};您也可以使用来自莫斯科的Vlad建议的语法来做到这一点:
You could also do this using the syntax suggested by Vlad from Moscow:
int A[5][5]; int B[5][5]; int (*C[])[5] = {A, B};该C声明被读为" C是指向int [5]数组的指针的数组".在这种情况下,C的每个数组元素都为int (*)[5]类型,而int [5][5]类型的数组可以衰减为该类型.
This declaration of C is read as "C is an array of pointers to int [5] arrays". In this case, each array element of C is of type int (*)[5], and array of type int [5][5] can decay to this type.
现在,您可以使用C[0][1][2]访问与A[1][2]相同的内存位置.
Now, you can use C[0][1][2] to access the same memory location as A[1][2].
此逻辑也可以扩展到更高的维度:
This logic can be expanded to higher dimensions as well:
int A[5][5][3]; int B[5][5][3]; int (*C[])[5][3] = {A, B};更多推荐
指向固定大小的数组的指针数组
发布评论