指向固定大小数组的指针数组 [英] Array of pointers to an array of fixed size
问题描述
我试图将两个固定大小的数组分配给指向它们的指针数组,但编译器警告我,我不明白为什么.
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};
这篇关于指向固定大小数组的指针数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!