第一个函数读取一个包含'char'的文件并将它们放入链表中。它不工作:(。为什么这个C链接列表程序给出'分段错误'?
#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;
}
固定的问题“文件”是零。
谢谢我现在解决了这个问题。 – ron 2010-02-18 23:39:06
别忘了'elem = list'分配一个值。如果你希望'list'更新时更新'elem',你需要在Jerry的版本中将'elem'改成原始代码中的'element ** elem =&list'或'element ** elem = list'。 – MSN 2010-02-19 05:42:50