遍历 raylib 中的链表会出现分段错误(核心已转储)

问题描述 投票:0回答:1

我正在尝试在 Raylib 应用程序中绘制文本。当我遍历链接列表时,其中的内容要么应用程序不打印任何内容,要么给出分段错误(核心转储)

案例 1:分段错误(核心转储)

#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;
        while (70 > pos) {
            DrawText(first->name, 20, pos, 14 ,WHITE);
            pos = pos + 20;
            first = first->next;
        }
        EndDrawing();
    }
    return 0;
}

此代码打印文本,但应用程序崩溃并给出分段错误(核心转储)

情况 2:不打印任何内容

#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;
        while (first) {
            DrawText(first->name, 20, pos, 14 ,WHITE);
            pos = pos + 20;
            first = first->next;
        }
        EndDrawing();
    }
    return 0;
}

这不会打印任何内容,但应用程序不会崩溃。

我尝试打印链接列表的元素数据。如果有人可以请告诉我我做错了什么

c linked-list segmentation-fault coredump raylib
1个回答
0
投票

我不了解 Raylib,但是...

在第一种情况下,很明显您正在第二次遍历

while (!WindowShouldClose())
而不重置
first
指针。内部
while (first)
的三个迭代很好地解决了,但是随后您只是指向任何内容(
first->next
已变为 NULL),并且在外部循环的第二遍开始处的行
DrawText(first->name, 20, pos, 14 ,WHITE);
触发了分段错误。

无论如何,在没有事先测试过

first = first->next
的情况下,您不应该前进指针 (
first->next != NULL
)。或者,如果您在指针中接受 NULL(您的选择),则应该验证
first != NULL
before 访问
first->name
first->next

© www.soinside.com 2019 - 2024. All rights reserved.