【问题标题】:How to implement a 2-dimensional array of struct in C如何在 C 中实现二维结构数组
【发布时间】:2011-03-17 13:34:11
【问题描述】:
我目前正在尝试了解如何在 C 中实现二维结构数组。我的代码一直在崩溃,我真的要让它结束,就像我所有的方法都变得坚定 C: 垃圾.这是我得到的:
typedef struct {
int i;
} test;
test* t[20][20];
*t = (test*) malloc(sizeof(test) * 20 * 20);
我光荣的错误:
错误:从“struct test *”类型分配给“struct test *[20]”类型时类型不兼容
我必须为每个二维单独分配内存吗?我快疯了。应该很简单。有一天我会建造一台时间机器并磁化一些 c-compiler-floppies...
【问题讨论】:
标签:
c
struct
multidimensional-array
【解决方案1】:
这就够了:
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));
【解决方案2】:
test **t;
t = (test **)malloc(sizeof(test *) * 20);
for (i = 0; i < 20; i++) {
t[i] = (test *)malloc(sizeof(test) * 20);
}
【解决方案3】:
根据我的观察,您可能并不确切知道自己想要什么,并对结构和指针算法感到困惑。请通过以下两种可能性。
1) 每个元素的二维数组都有一个指向test 的指针。
在这种情况下,所有指向tests 的指针的内存都已静态分配。
但是,真正的tests的记忆还没有准备好。
在这种情况下,您必须一一填写test [i][j]。
每个test 在内存中都是离散的,您可以动态地单独创建或销毁它们。
typedef struct {
int i;
} test;
test* t[20][20];
/* or instead of statically allocated the memory of all the pointers to tests
you can do the following to dynamically allocate the memory
test ***t;
t = (test***)malloc(sizeof(test *) * 20 * 20);
*/
for (int i=0; i < 20; i++){
for (int j=0; j < 20; j++){
t[i][j] = malloc(sizeof(test));
}
}
2) 每个元素的二维数组是test。
在这种情况下,所有tests 的内存都已分配。
此外,真正的tests的内存无需额外准备即可使用。
所有的tests 在内存中作为一个大块是连续的并且一直存在。这意味着如果您只在某个高峰时间需要所有tests,并且大多数时候您只使用其中的几个,那么您可能会浪费大量内存。
typedef struct {
int i;
} test;
test t[20][20];
/* or instead of statically allocated the memory of all tests
you can do the following to dynamically allocate the memory
test **t;
t = (test**)malloc(sizeof(test) * 20 * 20);
*/
【解决方案4】:
其他答案显示了如何解决它,但没有解释原因。正如编译器所暗示的那样,您原始示例中 t 的类型实际上是 test *[20] 这就是为什么您将其转换为 test * 是不够的。
在 C 中,维数为 N 的数组 T 的名称实际上是 *T[dim0][dim1]...[dimN-1] 类型。有趣。
【解决方案5】:
此外,只要您的内部维度大小不变,您就可以分配可变数量的内部维度计数
int n = ...;
test (*t)[20] = malloc(sizeof (*t) * n);
t[0 .. (n-1)][0 .. 19] = ...;