如何在C中实现结构的二维数组C
我目前正试图了解如何在C中实现一个二维数组结构。我的代码一直崩溃,我真的要让它结束就像我所有的方法都坚定地使用C:垃圾。这是我的了:如何在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 *’
我必须seperately分配的内存每2维?我越来越疯了。它应该是如此简单。有一天,我将建立一个时间机器和磁化一些C编译器,软盘...
这应该是足够了:
typedef struct {
int i;
} test;
test t[20][20];
这将申报的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));
其他答案显示如何解决它,但他们没有解释为什么。正如编译器暗示的那样,原始示例中t
的类型实际上是test *[20]
,这就是为什么您投到test *
还不够。
在C中,维数N的数组T的名称实际上是*T[dim0][dim1]...[dimN-1]
类型。乐趣。
从我的观察,你可能不知道你想要什么,并混淆了结构和指针算术。请通过以下2种可能性。
1)具有每个元素的二维数组具有指向test
的指针。 在这种情况下,内存的所有指针test
s已经静态地被分配为。 但是,内存的真实test
s尚未准备好。 在这种情况下,您必须逐个填写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
s已经分配。 此外,内存的真实test
s准备使用没有额外的准备。
所有的test
都是作为一个大块连续存储在内存中,并始终存在。这意味着如果您在某个高峰时间只需要所有的test
s,并且大部分时间只使用其中的一部分,则可能浪费大量内存。
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] = ...;
非常感谢! – Mortezaipo 2017-01-17 21:55:14