Pen*_*per 11 c struct multidimensional-array
我目前正在尝试理解如何在C中实现结构的二维数组.我的代码一直在崩溃,我真的要让它像我所有的方法一样坚定到C:垃圾.这就是我得到的:
typedef struct {
int i;
} test;
test* t[20][20];
*t = (test*) malloc(sizeof(test) * 20 * 20);
Run Code Online (Sandbox Code Playgroud)
我的光荣错误:
错误:从类型'struct test*'分配类型'struct test*[20]'时出现不兼容的类型
我是否必须为每个第二维单独分配内存?我疯了.应该这么简单.有一天,我将构建一个时间机器并磁化一些c-compiler-floppies ......
IVl*_*lad 24
这应该足够了:
typedef struct {
int i;
} test;
test t[20][20];
Run Code Online (Sandbox Code Playgroud)
这将声明一个test大小为20 x 20 的二维数组.不需要使用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));
Run Code Online (Sandbox Code Playgroud)
test **t;
t = (test **)malloc(sizeof(test *) * 20);
for (i = 0; i < 20; i++) {
t[i] = (test *)malloc(sizeof(test) * 20);
}
Run Code Online (Sandbox Code Playgroud)