为什么这个C链表程序会给出"分段错误"?

0 c linked-list

第一个函数读取一个包含一堆'char'的文件,并将它们放在一个链表中.它无法正常工作:(.

#include <stdio.h>
#include <stdlib.h>

struct list {
    char val;
    struct list* next;
};

typedef struct list element;

int lcreate(char* fname, element* list);
int ldelete(element* list);
int linsert(char a, char b, element* list);
int lremove(char a, element* list);
int lsave(char* fname, element* list);



int lcreate(char* fname, element* list) {
    element* elem = list;
    char c = 0;
    FILE * file = NULL;

    file = fopen(fname, "r");

    while ((c = getc(file)) != EOF)
    {
        if(list == NULL) {
            list = (element*)malloc(sizeof(element));
            if(list == NULL) {
                return 0;
            }
            list->val = c;
        }
        else {

            elem->next=(element*)malloc(sizeof(element));
            elem = elem->next;
            elem-> val = c;
        }
    }
    fclose(file);
    elem->next = NULL;
    return 1;
}



int main(void) {
    int i = 0;


    element * list = NULL;
    lcreate("list.txt", list);

    for(i = 0; i<4; ++i) {
        printf("%c", list->val);
        list = list->next;
    }

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

修复了'file'为空的问题.

Jer*_*fin 6

一个明显的问题就在这里:

FILE * file = NULL;

fopen(fname, "r");
Run Code Online (Sandbox Code Playgroud)

为了fopen实现这一目标,您需要将结果分配fopen给您FILE *:

file = fopen(fname, "r");
Run Code Online (Sandbox Code Playgroud)

编辑:由于您在C中工作,因此无法通过引用传递指针.作为替代方法,您可以将指针传递给指针:

int lcreate(char *fname, element **list) {

     // ...
     *list = malloc(sizeof(element));
     (*list)->next = null;
     (*list)->val = c;
// ...
}
Run Code Online (Sandbox Code Playgroud)

基本上,里面的所有代码lcreate都需要引用*list而不仅仅是list.或者,您可以将指向现有列表的指针作为输入,并返回指向列表的指针,因此main您需要具有以下内容:list = lcreate("list.txt", list);