gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 16:42:30 25 4
gpt4 key购买 nike

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com