有人可以给我解释一下吗?指针是我目前正在上的课中最令人困惑的部分。
我有一个结构,我想包含指向另一个结构 npc_t
的指针数组,就像这样
typedef struct dungeon {
int num_monsters;
struct npc_t *monsters;
} dungeon;
然后我想在初始化一个新怪物时为数组monsters
动态分配空间。我目前有
//add to dungeon's list of monsters
realloc(d->monsters, d->num_monsters);
d->monsters(d->num_monsters) = m;
d->num_monsters++;
其中 num_monsters
被初始化为 0。
我在编译时收到这条消息
npc.c: In function ‘init_monster’:
npc.c:65:13: error: called object is not a function or function pointer
d->monsters(d->num_monsters) = m;
^
npc.c:64:9: warning: ignoring return value of ‘realloc’, declared with attribute warn_unused_result [-Wunused-result]
realloc(d->monsters, d->num_monsters);
^
make: *** [npc.o] Error 1
我的做法是否正确?我可以使用 d->monsters(d->num_monsters)
和 d->monsters(i)
之类的东西来抓取我想要的怪物吗? (例如,如果 i
是 for 循环中的一些增量)
最佳答案
这个:
realloc(d->monsters, d->num_monsters);
应该是:
d->monsters = realloc(d->monsters, d->num_monsters * sizeof *d->monsters);
sizeof
非常重要,没有它,您将大量分配不足,这将导致未定义的行为,因为您的代码写入分配的存储空间之外。
此外,正确的数组索引语法是a[i]
,括号用于函数调用。
关于c - 为指针数组动态分配空间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28688379/