使用 malloc 初始化结构内部的结构?

Initializing structs inside a struct with malloc?

这是我的 NPC 数据结构。

typedef struct npc {
   npc_characteristics_t characteristics;
   position pc_last_known_position;
   position npc_position;
   int speed;
   int turn;
} npc_t;

我用这个初始化它:

void gen_monsters(dungeon *d, int nummon) {
  int i;
  for (i = 0; i < nummon; i++) {
    npc_t *monster;
    if (!(monster = malloc(sizeof (*monster)))) {
      perror("malloc");
      exit(1);
    } else {
      init_monster(monster);
    }
  }
}

static void init_monster(npc_t *m) {
  int charact = rand()%3;

  if (charact == 0) 
    m->characteristics = 0x00000000;
  else if (charact == 1)
    m->characteristics = NPC_SMART;
  else if (charact == 2)
    m->characteristics = NPC_TELEPATH;

  m->pc_last_known_position = {0, 0};
  m->npc_position = {0, 0};
  m->speed = rand() % 15 + 6;
  m->turn = 0;
}

这是我的 position 结构:

typedef struct position_t {
  int x, y;
} position;

为什么这不起作用?我得到这个:

npc.c:22:1: error: expected identifier or ‘(’ before ‘}’ token
 }
 ^
npc.c: In function ‘init_monster’:
npc.c:35:30: error: expected expression before ‘{’ token
  m->pc_last_known_position = {0,0};
                          ^
npc.c:37:20: error: expected expression before ‘{’ token
  m->npc_position = {0,0};
                    ^
make: *** [npc.o] Error 1

正确的做法是什么?我应该使用 malloc 为结构在内存中腾出一些空间,对吗?但是我不需要为 position 做这个并给 NPC 指向 position 结构的指针吗?

虽然您不能那样使用初始化列表,但您可以使用 string.h header 中的 memset() 函数,这样

memset(&(m->pc_last_known_position), 0, sizeof(m->pc_last_known_position));
memset(&(m->npc_position), 0, sizeof(m->pc_last_known_position));