I declared a simple Entity (node) structure like this, and an head and tail pointers
- {l Code}: {l Select All Code}
typedef struct _Entity {
int id;
float x, y;
int w, h;
struct _Entity *next;
[...]
} Entity;
Entity *headList, *tailList;
After that, I create every single new entity (node) with this function
- {l Code}: {l Select All Code}
void createEntity(int id, int x, int y, int w, int h)
{
Entity *pnew = (Entity*) malloc(sizeof(Entity));
if(headList == NULL)
{
pnew->id = 1;
headList = pnew;
tailList = headList;
}
else
{
pnew->id = tailList->id+1;
tailList->next = pnew;
tailList = pnew;
}
tailList->next = NULL;
}
After some entities (nodes) are created, I loop over them with a function like this, along with some logical functions:
- {l Code}: {l Select All Code}
void doGame()
{
input();
movePlayer();
Entity *entity = headList, *temp=NULL, *previous=NULL;
while(entity!=NULL)
{
if(entity->active==1)
{
entity->update(entity);
doEntityGravity(entity);
if(rectCollision(Player.x, Player.y, Player.w, Player.h,
entity->x, entity->y, entity->w, entity->h))
{
if(headList==entity)
{
headList = entity->next;
}
else if(tailList==entity)
{
previous->next=NULL;
}
else
{
previous = entity->next;
free(entity);
entity = previous->next;
}
}
}
previous = entity;
entity = entity->next;
}
}
I loop over every entities (nodes) from head to tails, check if they collide with the player and try to destroy them from the list.
I have a problem here in trying to make it all work properly, things work correctly if i destroy the entities in the correct order, from head to tail, but having a segfault if trying to destroy e middle list entity.
Anyone have an idea on how to fix this?
Or is there a best practice for using singly linked lists in games?