C calling function on contents of linked list

痴心易碎 提交于 2019-12-12 04:35:55

问题


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.



来源:https://stackoverflow.com/questions/43441064/c-calling-function-on-contents-of-linked-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!