在Raylib中遍历链表触发段错误或无输出问题求助
Raylib链表遍历绘制文本的错误分析与修复
案例1:Segmentation fault 错误原因
代码在主循环的每一轮都会修改全局的first指针,循环条件70 > pos会触发3次循环(pos从20→40→60),此时first会被移动到链表最后一个节点的next(即NULL)。下一轮主循环执行时,代码再次访问first->name,而first已经是NULL,直接触发段错误。
案例2:无输出错误原因
同样是因为主循环每一轮都修改全局的first指针。第一次主循环执行时,while(first)会遍历完整个链表,把first变成NULL。之后的每一轮主循环中,while(first)的条件永远不成立,不会执行DrawText,所以看不到任何输出。
修复方案
核心是不要修改全局的first指针,改用临时指针遍历链表,确保每次主循环都能从链表头部开始遍历。修改后的代码如下:
#include "raylib.h" #include <stdio.h> #include <stdlib.h> struct Node { char *name; struct Node* next; }; struct Node *first = NULL; void create(char *array[] ,int n){ struct Node *node , *last; first = (struct Node *)malloc(sizeof(struct Node)); first->name = array[0]; first->next = NULL; last = first; for(int i = 1 ; i < n ; i++){ node = (struct Node *)malloc(sizeof(struct Node)); node->name = array[i]; node->next = NULL; last->next = node; last = node; } } int main(void){ char *array[] = {"First","Second","third"}; InitWindow(800,600,"Test"); SetTargetFPS(60); create(array, 3); while (!WindowShouldClose()) { BeginDrawing(); ClearBackground(DARKGRAY); int pos = 20; // 使用临时指针temp遍历,不修改全局first struct Node *temp = first; while (temp) { DrawText(temp->name, 20, pos, 14 ,WHITE); pos += 20; temp = temp->next; } EndDrawing(); } return 0; }
关键修改点
- 新增临时指针
struct Node *temp = first;,每次主循环都从链表头部开始遍历 - 遍历过程中操作
temp指针,保留first作为链表头部的固定引用 - 用
temp作为循环判断条件,避免访问超出链表范围的内存
内容的提问来源于stack exchange,提问作者yahya kamran
相关产品推荐
相关产品推荐

