我是 c 语言的新手,想制作一个可以从 txt 文件中读取链表的程序。例如,我的文件是这样的
0 1 6 4 8 6 8 15 56 4 864 68
我想阅读信息,然后尝试将其显示给用户。 这就是我所做的。这给了我错误,它在我声明的主要部分写入它之前的 head 预期表达式。
A = readList(head);
printList(head);
我的代码:
#include <stdio.h>
#include <stdlib.h>
typedef struct linkedList{
int value;
struct linkedList *next;
} linkedList, head;
linkedList *readList(linkedList *head)
{
FILE *dataFile;
dataFile = fopen("duom.txt", "r");
if(dataFile == NULL) {
printf("Nepasisekė atidaryti failo\n");
} else {
printf("Duomenų failą pavyko atidaryti\n");
}
while (!feof (dataFile))
if (head == NULL) {
head = malloc(sizeof(linkedList));
fscanf(dataFile, "%d", &head -> value);
head -> next = NULL;
} else {
struct linkedList *current = head;
struct linkedList *temp = malloc(sizeof(linkedList));
while(current -> next != NULL) {
current = current -> next;
}
fscanf(dataFile, "%d", &temp -> value);
current -> next = temp;
temp -> next = NULL;
}
return head;
}
void printList(linkedList *head)
{
linkedList *current = head;
while (current != NULL) {
printf("%d->", current -> value);
current = current -> next;
}
printf("NULL\n");
return;
}
int main()
{
linkedList A;
A=readList(head);
printList(head);
return 0;
}
最佳答案
您正在为 readList 中的 head 分配空间,但您正在那里传递一些不存在的参数(readList(head) 和 printList(head))。你可以做些什么来解决你的问题: 将您的主要更改为:
int main()
{
linkedList *A = NULL; /* creating pointer to your linked list. */
A=readList(A); /* Read linked list from file (And allocate it if it's not allocated */
printList(A); /* print list */
return 0;
}
如果您希望 A 全局可访问,只需将指针 A 的声明移到 main 之外。
关于c链表从txt文件读取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41227292/