我正在编写一个从文件中获取信息并将其添加到链表的程序,以及一个将信息添加到链表的函数。我的问题是,当我在 openBook()
之后调用 addContact()
时,程序崩溃了,但是分别调用它们都可以正常工作。
我找不到问题。
openBook()
: 打开文件,从文件读取数据到链表
addContact()
:获取信息,将数据保存到 linkedList
#include <stdio.h>
typedef struct node {
char name[50];
char email[50];
char ad[200];
char phone[11];
struct node *next;
} NODE;
NODE *head = NULL;
void openBook()
{
FILE *read = fopen("Book.txt", "r");
if (read == NULL)
{
return;
}
NODE *ite = NULL;
char name[50] = "", email[50] = "", ad[200] = "", phone[11] = "";
if (!feof(read))
{
head = (NODE*)malloc(sizeof(NODE));
fscanf(read, "%s%s%s%s", head->name, head->email, head->ad, head->phone);
}
ite = head;
while (!feof(read))
{
ite->next = (NODE*)malloc(sizeof(NODE));
ite = ite->next;
fscanf(read, "%s%s%s%s", ite->name, ite->email, ite->ad, ite->phone);
}
ite->next = NULL;
fclose(read);
}
void addContact()
{
NODE *ite = head;
if (head != NULL)
{
while (ite->next!=NULL)
ite = ite->next;
ite->next = (NODE*)malloc(sizeof(NODE*));
ite = ite->next;
}
else
{
head = (NODE*)malloc(sizeof(NODE*));
ite = head;
}
fflush(stdin);
printf("Enter name (no space): ");
scanf("%s", ite->name);
fflush(stdin);
printf("Enter email : ");
scanf("%s", ite->email);
fflush(stdin);
printf("Enter address : ");
scanf("%s", ite->ad);
fflush(stdin);
printf("Enter phone : ");
scanf("%s", ite->phone);
fflush(stdin);
ite->next = NULL;
}
void printList()
{
NODE *iterator;
int i;
iterator = head;
while (iterator != NULL)
{
printf("%s\n", iterator->name);
iterator = iterator->next;
}
}
int main()
{
openBook();
addContact();
printList();
return 0;
}
以下作品令人惊叹:
int main()
{
addContact();
printList();
return 0;
}
但以下崩溃:
int main()
{
FILE *read = fopen("Book.txt", "r");
fclose(read);
addContact();
printList();
return 0;
}
最佳答案
首先,有3点值得注意:
看来你错过了#include <stdlib.h>
.您应该已经收到来自编译器的警告,提示缺少 malloc()
的声明。 .
修复丢失的 header 后,我无法重现您的问题。我创建了一个 Book.txt
该程序运行良好。
这是我的 Books.txt
用于测试。
aaa aaa aaa aaa
aaa aaa aaa aaa
aaa aaa aaa aaa
aaa aaa aaa aaa
aaa aaa aaa aaa
我用于测试的输入:
aaa aaa aaa aaa
关于处理文件和链接列表时崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48076991/