C calling function on contents of linked list

2019-09-14 20:35发布

问题:

I am using GLib to manage a linked list. I am declaring 2 structs and the placing them in a linked list as follows.

Asteroid asteroid = {0,0,50,50,50}
Asteroid asteroids = {0,0,200,200,50};

GList *asteroidList = NULL;
asteroidList = g_list_append(asteroidList, &asteroid);
asteroidList = g_list_append(asteroidList, &asteroids);

Then i use the following function to traverse the list and calla function that draws the struct to the screen as a circle as follows

void drawAsteroids(){
GList *list = asteroidList;
while(list != NULL){
    printf("Asteroids");
    GList *next = list->next;
    drawAsteroid(list->data);
    list = next;
  }
}

The drawing function is

void drawAsteroid(void *asteroid){
    Asteroid *newAsteroid = (Asteroid *)asteroid;
    printf("%d\n", newAsteroid->xPos);
    circleRGBA(renderer, newAsteroid->xPos, newAsteroid->yPos, newAsteroid->r, 0, 255, 0, 255);
}

The struct is defined as follows

typedef struct asteroid{
    int xSpeed;
    int ySpeed;

    int xPos;
    int yPos;

    int r;
}Asteroid;

When i run this code i dont see anything drawn to the screen

回答1:

The GList functions do not copy the data. If you place the Asteroid structure on the stack, and it goes out of scope, then the list->data pointer will point to garbage.

You need to allocate the data on the heap, and then remember to free it when not needed any more.