指向多维数组的指针数组
我有一些二维数组,如:
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};
有帮助吗?
更新固定类型。 感谢j_radom_hacker
将此引起我的注意!
[编辑:实际上这里的类型不正确 – 请参阅Robert S. Barnes对正确使用类型的回答 。]
首先shape1
和shape2
的类型:
typedef int (*shape_array_t)[5];
现在用这个:
shape_array_t sat[] = { shape1, shape2 };
我相信我刚刚validation了我写的是正确的。 以下按预期工作:
#include 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个相邻的arrays,每个5个整数。 但实际类型是指向5个整数的数组。 当你写:
shape1[1][2] = 1;
你告诉编译器索引到第二个int [5]数组,然后访问该数组的第3个元素。 编译器实际上做的是指向底层类型的指针算法,在本例中为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];
首先,第一个数组绑定是指最外层的数组维度,因此您应该将shape1
声明为:
int shape1[5][3] = {1,0,0, 1,0,0, 1,0,0, 1,0,0, 1,0,0};
并且类似于shape2
。
[编辑:我已经改变了下面的shapes
类型以对应罗伯特巴恩斯的答案 – 我们不希望最外面的下标包含在这种类型中!]
你需要的略带奇怪的类型名称是:
int (*shapes[])[3] = { shape1, shape2 };
这允许使用shape2
2的第4行第1列的元素进行寻址
shapes[1][3][0]
子表达式及其C类型的细分:
shapes // has type "int (*x[2])[3]" (decays to "(**x)[3]") shapes[1] // has type "int (*x)[3]" shapes[1][3] // has type "int x[3]" (decays to "int *x") shapes[1][3][0] // has type "int x"
(请注意,上面的类型中包含了一个虚拟x
以使它们更清晰 – 实际上这个标识符不属于该类型。)
解码C / C ++类型的经验法则是“从变量名开始,在可以时读右,在到达右括号时离开。” 所以shapes
的解码型名称是:
指向3个整数数组的指针数组。
一般来说,对于这些复杂类型使用typedef
要好得多,正如dirkgently建议的那样 。