c - 链表崩溃

标签 c data-structures linked-list

我正在尝试做一个关于链表的例子。首先,我将值添加到变量中,没有问题。但是当我试图从用户那里获取值时,程序在进入 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/

相关文章:

java - 迭代器打印链表

java - 为什么Java中的浮点计算比C慢

c - 用C实现 "strings"的堆栈

c - 堆栈中的最小值

algorithm - 发布-订阅系统的设计/代码调度程序

c - C 中的简单链表实现

c - 使用 GCC 查找生成和终止集

c - go 中的 xslt 支持

algorithm - 如何计算循环图的密度?

c++ - 在 C++、结构或类中应该使用什么来创建链接列表