c - 为指针数组动态分配空间

标签 c arrays pointers realloc

有人可以给我解释一下吗?指针是我目前正在上的课中最令人困惑的部分。

我有一个结构,我想包含指向另一个结构 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/

相关文章:

c - 没有它们如何获取 GetProcAdress 和 LoadLibrary?

c - 在函数中使用 static

arrays - 如何在 Groovy 中转置矩阵?

c++ - Valgrind:来自复制构造函数的大小为 8 的无效写入

c - C 中指针减法期间的除法

c - C 中堆栈操作中的指针变量与全局变量

c - 错误地传递参数? C题

c - 指针指向字符串时没有输出

c - 自定义文件打开函数在 Linux 内核中覆盖 sys_call_table 时的奇怪行为

arrays - 明智地聚合数组元素