如何在C中实现struct的二维数组
我目前正在尝试理解如何在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 ……
这应该足够了:
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));
test **t; t = (test **)malloc(sizeof(test *) * 20); for (i = 0; i < 20; i++) { t[i] = (test *)malloc(sizeof(test) * 20); }
其他答案显示如何解决它,但他们没有解释原因。 正如编译器暗示的那样,原始示例中的t
类型实际上是test *[20]
,这就是为什么你的演员test *
是不够的。
在C中,维数N的数组T的名称实际上是*T[dim0][dim1]...[dimN-1]
。 乐趣。
根据我的观察,你可能不知道你想要什么,并混淆结构和指针算术。 请仔细阅读以下两种可能性。
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
,并且大多数时间只使用其中一些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); */
此外,只要您的内部维度大小不变,您就可以分配该内部维度的可变数量的计数
int n = ...; test (*t)[20] = malloc(sizeof (*t) * n); t[0 .. (n-1)][0 .. 19] = ...;