The following code causes a SIGSEGV, but only while debugging.
#include <stdio.h>
#include <stdlib.h>
typedef struct enemy_desc
{
int type;
int x;
int y;
}enemy;
int main()
{
enemy **enemies;
enemies=(enemy **)malloc(sizeof(enemy *)*16);
enemies[0]->type=23;
printf("%i",enemies[0]->type);
return 0;
}
You have allocated memory for 16
enemy *pointers, but you have not allocated room for the 16enemystructs themselves. There are two ways to fix this. One is to add a loop that allocates each of the 16enemystructs one by one:The other is to remove one level of indirection. If you declare
enemy *enemiesthen you can allocate the 16 structs at once and forgo a loop. If there’s no need for the double indirection this would be my preferred solution:Notice that the
->operator switches to..