链接列表Appcrash

时间:2014-04-04 08:50:12

标签: c data-structures linked-list

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

2 个答案:

答案 0 :(得分:0)

修复1

删除行

while(node->next);

原因:在大多数情况下,它会让你无限循环,这是不必要的。


修复2

替换循环

while(node->next != NULL) {

}

if (node->next != NULL) {
    while (node->next->next != NULL) {

    }
}

原因:您每次都要分配一个额外的结构,并将其保留为空,以便下次阅读。因此,链接列表将在下一个变为NULL之前结束。


修复3

在struct

中替换以下内容
char *name;

char name[80];

原因:内存未分配。


修复4

替换所有scanfname除外)

scanf("%d", node->m1);

scanf("%d", &node->m1);

原因: scanf需要读取数据的内存位置。

祝你好运

答案 1 :(得分:0)

您的代码有多处错误。

首先,第一个scanf("%s", node->name)缺少终止分号。

接下来,您的功能签名很草率。 main()应为int main(void)addStudent()应为int addStudent(void)。 (或者,摆脱它的return 0并让它返回void。)因为你没有预先声明addStudent(),所以你应该在main()之前定义它。 main()可以了解它。

但是,崩溃是因为你还没有为node->name分配内存。您已为node分配了内存,但这并没有为您提供放置名称的空间。

相关问题