如何在C语言中实现一个二维结构体数组

16

我目前正在尝试理解如何在C语言中实现一个二维结构体数组。我的代码一直崩溃,我真的快要放弃了,感觉自己对C语言的掌握程度就像垃圾一样。以下是我的代码:

typedef struct {
    int i;
} test;

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

我的荣耀性错误:

错误:将类型为“struct test *”的值分配给类型为“struct test *[20]”的变量

我是否必须为每个第二维度单独分配内存?我要发疯了。这应该很简单。有一天我会建造一台时间机器并磁化一些C编译器软盘...

5个回答

31
这应该足够了:
typedef struct {
    int i;
} test;

test t[20][20];

这将声明一个大小为20x20的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));

非常感谢您! - mortymacs

11
test **t;

t = (test **)malloc(sizeof(test *) * 20);
for (i = 0; i < 20; i++) {
   t[i] = (test *)malloc(sizeof(test) * 20);
}

4
根据我的观察,您可能不确定自己想要什么,并且对结构和指针算术感到困惑。请查看以下两种可能性。
1)一个二维数组,每个元素都有一个指向“test”的指针。 在这种情况下,“所有指向‘test’的指针”的内存已经被静态地分配了。 但是,“真正的‘test’内存”还没有准备好。 在这种情况下,您必须逐个填写“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。在这种情况下,所有test的内存已经被分配。另外,真正的test的内存也已准备好,无需额外准备。

所有的test在内存中作为一个大块连续存在,并且始终存在。这意味着如果你只在某个峰值时间需要所有的test,而大部分时间只使用其中的少数,则可能浪费一部分内存。

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] 的指针。很有趣。


0

此外,只要您的内部维度大小是恒定的,您就可以分配可变数量的该内部维度计数

int n = ...;
test (*t)[20] = malloc(sizeof (*t) * n);
t[0 .. (n-1)][0 .. 19] = ...;

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接