c - 指向多维数组的指针数组

标签 c arrays pointers

我有一些二维数组,例如:

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]);

}

要记住的是 shape1shape2 的类型实际上是:

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/

相关文章:

C - 按迭代位置将两个数组合并为一个

c - C 程序中整数的奇怪行为

c - 数百万 UINT64 RGBZ 图形像素的最快排序算法

python - 在不创建辅助数组的情况下使用 imshow 绘制数组时,将特定颜色分配给数组的值

c++ - C++ 中的引用在内部编译为指针还是别名?

c - 从 fork() 返回 -1

ios - 如何在 Swift 中对 simd_float4x4 元素数组进行编码(将 simd_float4x4 转换为数据)?

Javascript 扫雷游戏,无法增加正确的单元格

c++ - 将 argv 与函数一起使用时出错

c - 为什么使用此 C 代码会出现段错误?