gpt4 book ai didi

c - 为什么这个 C 链表程序给出 'segmentation fault' ?

转载 作者:太空宇宙 更新时间:2023-11-04 05:11:25 25 4
gpt4 key购买 nike

第一个函数读取一个包含一堆“字符”的文件,并将它们放入链表中。它不工作:(。

#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;
}

修复了 'file' 为 null 的问题。

最佳答案

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

FILE * file = NULL;

fopen(fname, "r");

要让 fopen 完成很多工作,您需要将 fopen 的结果分配给您的 FILE *:

file = fopen(fname, "r");

编辑:由于您使用的是 C 语言,因此无法通过引用传递指针。作为替代方案,您可以将指针传递给指针:

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

// ...
*list = malloc(sizeof(element));
(*list)->next = null;
(*list)->val = c;
// ...
}

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

关于c - 为什么这个 C 链表程序给出 'segmentation fault' ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2293033/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com