Reputation: 374
Here is my data structure for an NPC.
typedef struct npc {
npc_characteristics_t characteristics;
position pc_last_known_position;
position npc_position;
int speed;
int turn;
} npc_t;
I initialize it with this:
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;
}
And this is my position
struct:
typedef struct position_t {
int x, y;
} position;
Why isn't this working? I'm getting this:
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
And what's the correct way to do this? I'm supposed to use malloc
to get some room in memory for the structure right? But then wouldn't I need to do this for position
also and give the NPC the pointer to the position
struct?
Upvotes: 2
Views: 480
Reputation: 53006
Although you can't use an initializer list that way, you can use the memset()
function from the string.h
header, this way
memset(&(m->pc_last_known_position), 0, sizeof(m->pc_last_known_position));
memset(&(m->npc_position), 0, sizeof(m->pc_last_known_position));
Upvotes: 2