我有一些二维数组,如:
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};
Run Code Online (Sandbox Code Playgroud)
等等.
我如何制作一系列指针?
我尝试了以下,但它们不起作用(警告:从不兼容的指针类型初始化):
int *shapes[]= {&shape1,&shape2};
int *shapes[]= {shape1,shape2};
int **shapes[]= {&shape1,shape2};
Run Code Online (Sandbox Code Playgroud)
有帮助吗?
我相信我刚刚验证了我写的是正确的.以下按预期工作:
#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]);
}
Run Code Online (Sandbox Code Playgroud)
要记住的是,类型shape1和shape2实际上是:
int *shape1[5];
你在记忆中拥有的是3个相邻的阵列,每个阵列有5个整数.但实际类型是指向5个int的数组.当你写:
shape1[1][2] = 1;
你告诉编译器索引到第二个int [5]数组,然后访问该数组的第3个元素.编译器实际上做的是指向基础类型的指针算法,在本例中为int [5].您可以使用以下代码执行相同的操作:
int *p = shapes1[0];
p+7 = 1; // same as shape1[1][2] = 1;
Run Code Online (Sandbox Code Playgroud)
所以如果你想要一个指向int*[5]的指针数组,那么你会这样做:
typedef int (*shapes_p)[5];
shapes_p shapes[2];
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6377 次 |
| 最近记录: |