我目前正在尝试了解如何在 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/