malloc 结构指针数组 [英] malloc an array of struct pointers
问题描述
我有以下结构:
typedef struct _chess {
int **array;
int size;
struct _chess *parent;
} chess;
我有:
typedef struct _chess *Chess;
现在,我想创建一个动态长度数组来存储指向国际象棋结构的指针,因此我执行以下操作:
Now, I want to create an array of dynamic length to store pointers to the chess struct so I do the following:
Chess array [] = malloc(size * sizeof(Chess));
这给了我一个错误:无效的初始值设定项.
This gives me an error: invalid initializer.
如果我删除 [] 并执行以下操作:
And if I drop the [] and do this:
Chess array = malloc(size * sizeof(Chess));
它编译没有错误但是当我尝试通过执行以下操作将此数组的元素设置为 NULL 时:
it compiles without error but when I try to set an element of this array to NULL by doing:
array[i]=NULL;
我收到一个错误:从类型‘void *’分配给类型‘struct _chess’时类型不兼容
I get an error: incompatible types when assigning to type ‘struct _chess’ from type ‘void *’
知道我做错了什么吗?谢谢.
Any idea what am I doing wrong? Thanks.
推荐答案
array
是一个有点误导的名称.对于动态分配的指针数组,malloc
将返回一个指向内存块的指针.您需要使用 Chess*
而不是 Chess[]
来保存指向数组的指针.
array
is a slightly misleading name. For a dynamically allocated array of pointers, malloc
will return a pointer to a block of memory. You need to use Chess*
and not Chess[]
to hold the pointer to your array.
Chess *array = malloc(size * sizeof(Chess));
array[i] = NULL;
也许以后:
/* create new struct chess */
array[i] = malloc(sizeof(struct chess));
/* set up its members */
array[i]->size = 0;
/* etc. */
这篇关于malloc 结构指针数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!