c - 如何在C中实现二维结构数组

标签 c struct multidimensional-array

我目前正在尝试了解如何在 C 中实现二维结构数组。我的代码一直在崩溃,我真的打算让它结束,就像我所有的方法都坚定地使用 C 一样:垃圾.这是我得到的:

typedef struct {
    int i;
} test;

test* t[20][20];
*t = (test*) malloc(sizeof(test) * 20 * 20);

我的光荣错误:

error: incompatible types when assigning to type ‘struct test *[20]’ from type ‘struct test *’

我是否必须为每个二维单独分配内存?我快疯了。它应该如此简单。有一天我会 build 一台时间机器并磁化一些 c-compiler-floppies...

最佳答案

这应该足够了:

typedef struct {
    int i;
} test;

test t[20][20];

这将声明一个大小为 20 x 20 的 test 二维数组。无需使用 malloc。

如果你想动态分配你的数组,你可以这样做:

// in a function of course
test **t = (test **)malloc(20 * sizeof(test *));
for (i = 0; i < 20; ++i)
    t[i] = (test *)malloc(20 * sizeof(test));

关于c - 如何在C中实现二维结构数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3275381/

相关文章:

c - sizeof(),C 结构中的对齐方式 :

c - C 中的矩阵乘法 - 使用的结构

php - 将多维嵌套 PHP 数组 reshape 为另一种格式

C:通过堆栈/寄存器问题返回值

c - 如何解决 "subscripted value is neither array nor pointer nor vector"

c - Realloc 结构数组作为函数参数产生段错误?

c - 多维数组不保存值

php - 将 mysql 值分配到多维数组中

c - 套接字应用程序无法接收 tcpreplay 发送的数据包

c - 算法 - 快速排序的实现问题