我有一些二维数组,例如:
int shape1[3][5] = {1,0,0,
1,0,0,
1,0,0,
1,0,0,
1,0,0};
int shape2[3][5] = {0,0,0,
0,0,0,
0,1,1,
1,1,0,
0,1,0};
等等。
我如何制作指向这些指针的数组?
我尝试了以下方法,但它们不起作用(警告:从不兼容的指针类型初始化):
int *shapes[]= {&shape1,&shape2};
int *shapes[]= {shape1,shape2};
int **shapes[]= {&shape1,shape2};
有什么帮助吗?
最佳答案
我相信我只是验证了我写的是正确的。以下按预期工作:
#include <stdio.h>
int main(int argc, char **argv) {
int shape1[5][3] = {1,0,0,
1,0,0,
1,0,0,
1,0,0,
1,0,0};
int shape2[5][3] = {0,0,0,
0,0,0,
0,1,1,
1,1,0,
0,1,0};
typedef int (*shapes_p)[3];
shapes_p shapes[2] = { shape1, shape2 };
shapes[0][1][0] = 5;
shapes[1][1][0] = 5;
printf("shape1[1][0] == %d\n", shape1[1][0]);
printf("shape2[1][0] == %d\n", shape2[1][0]);
}
要记住的是 shape1
和 shape2
的类型实际上是:
int *shape1[5];
内存中有 3 个相邻的数组,每个数组有 5 个整数。但实际类型是指向 5 个整数的数组的指针。当你写:
shape1[1][2] = 1;
你告诉编译器索引到 int[5] 的第二个数组,然后访问该数组的第三个元素。编译器实际做的是对指向的基础类型进行指针运算,在本例中为 int[5]。您可以使用以下代码执行相同的操作:
int *p = shapes1[0];
p+7 = 1; // same as shape1[1][2] = 1;
所以如果你想要一个指向 int *[5] 的指针数组,那么你会这样做:
typedef int (*shapes_p)[5];
shapes_p shapes[2];
关于c - 指向多维数组的指针数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/799373/