链表内容的C调用功能 [英] C calling function on contents of linked list
问题描述
我正在使用GLib管理链接列表.我声明了2个结构,并将它们放置在链接列表中,如下所示.
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);
然后,我使用以下函数遍历列表和calla函数,该函数将结构作为一个圆形绘制到屏幕上,如下所示:
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;
}
}
绘图功能是
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);
}
结构定义如下
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
推荐答案
GList
函数不会不复制数据.如果将Asteroid
结构放在堆栈上,并且超出范围,则list->data
指针将指向垃圾.
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.
这篇关于链表内容的C调用功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!