我正在尝试做一个关于链表的例子。首先,我将值添加到变量中,没有问题。但是当我试图从用户那里获取值时,程序在进入 midterm 2 年级时崩溃了。我尝试了其他输入功能,但结果是一样的。问题出在哪里?
#include <stdio.h>
struct student
{
char *name;
int m1,m2,final;
struct student* next;
};
main()
{
addStudent();
system("PAUSE");
}
addStudent()
{
struct student *node = NULL;
struct student *firstnode;
firstnode = (struct student *)malloc(sizeof(struct student));
node = firstnode;
printf("press 0 to exit \n");
while(1)
{
printf("Student name: ");
scanf("%s", node->name)
if(node->name == "0") break;
printf("Midterm 1: ");
scanf("%d", node->m1);
printf("Midterm 2: ");
scanf("%d", node->m2);
printf("Final: ");
scanf("%d", node->final);
node->next = (struct student *)malloc(sizeof(struct student));
node = node->next;
}
node->next = NULL;
node = firstnode;
while(node->next);
while(node->next != NULL)
{
printf("%s - ",node->name);
printf("%d ", node->m1);
printf("%d ", node->m2);
printf("%d ", node->final);
node = node->next;
}
system("PAUSE");
return 0;
}
最佳答案
修复 1
删除行
while(node->next);
原因:在大多数情况下,它会让你陷入死循环,这是不必要的。
修复 2
替换循环
while(node->next != NULL) {
}
与
if (node->next != NULL) {
while (node->next->next != NULL) {
}
}
原因:您每次都在分配一个额外的结构并将其保持为空以便下次读取。因此链表将在 next 变为 NULL 之前结束。
修复 3
替换结构中的以下内容
char *name;
与
char name[80];
原因:未分配内存。
修复 4
替换所有出现的scanf
(name
除外)
scanf("%d", node->m1);
与
scanf("%d", &node->m1);
原因:scanf
需要读取数据的内存位置。
祝你好运
关于c - 链表崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22857871/