分段故障核心转储[C语言,链表]

问题描述 投票:0回答:1

我想显示我的列表,但是,我的print()函数似乎有问题。请帮我!非常感谢。我试图创建一个带有单个链表的学生管理系统,下面只是两个函数,用于将数据输入到列表并在插入或删除任何内容之前显示它。据我所知,分段错误发生,因为我想访问我不允许的内存,但它是如此通用。我需要一些详细的解释和一些解决方案!

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define ID_LENGTH 5
#define NAME_LENGTH 51

typedef struct Student_t {
  char id[ID_LENGTH];
  char name[NAME_LENGTH];
  int grade;
  struct Student_t *next; 
} Student;

Student* head;

void input(){
  int n,i;
  Student* temp = (Student*) malloc(sizeof(Student*));
  printf("Enter the number of students: ");
  scanf("%d",&n);
  for(i=0;i<n;i++){
    printf("Enter the information of student no.%d\n",i+1);
    printf(" -ID: "); scanf("%s",&temp->id);
    printf(" -Name: "); //getchar(); gets(temp->name); //
    scanf("%s",&temp->name);
    printf(" -Grade: "); scanf("%d",&temp->grade);
  }
}

void print(){
  Student* temp = (Student*) malloc(sizeof(Student*));
  temp = head;
  printf("\t\tThe Student List\n\n");
  printf("%-10s%-40s%-10s\n","ID","Name","Grade");
  while(temp->next != NULL){  
    printf("%-10s%-40s%-10d\n",temp->id,temp->name,temp->grade);
    temp = temp->next;
  }
}
int main(){
  // head = NULL; //empty list
  input();  
  print();
}
c data-structures printing linked-list segmentation-fault
1个回答
0
投票

当您实现链接列表时,请始终使用笔和纸,并在开始编码之前正确记下每一步。编写创建列表,插入新节点,删除节点的每个步骤。永远不要忘记在创建新节点时将next指针指定为NULL。大多数时候问题总是与next一样,因为你的列表的最后一个节点的next被分配了垃圾值而不是NULL。

现在首先纠正以下声明。在这里你应该提供结构名称而不是指针: -

Student* temp = (Student*) malloc(sizeof(Student));
temp->next = NULL;//always do it
head = temp;// now head is pointing to the first node of the list

你的下面for循环是完全错误的。你没有在这里创建一个列表。您一直在使用相同的节点。

for(i=0;i<n;i++){
printf("Enter the information of student no.%d\n",i+1);
printf(" -ID: "); scanf("%s",&temp->id);
printf(" -Name: "); //getchar(); gets(temp->name); //
scanf("%s",&temp->name);
printf(" -Grade: "); scanf("%d",&temp->grade);

}

纠正它如下: -

int i = 0;
while(1){       
printf("Enter the information of student no.%d\n",i+1);
printf(" -ID: "); scanf("%s",&temp->id);
printf(" -Name: "); //getchar(); gets(temp->name); //
scanf("%s",&temp->name);
printf(" -Grade: "); scanf("%d",&temp->grade);
if( ++i < n ){// each time you have to create a new node
   temp->next = (Student*) malloc(sizeof(Student));
   temp = temp->next;
   temp->next = NULL;
}
else
   break;
}

纠正你的print功能如下: -

void print(){
  Student* temp = head;// here you no need to create a new node. Just create a node which will point to the head
  printf("\t\tThe Student List\n\n");
  while(temp != NULL){  
    printf("%-10s%-40s%-10d\n",temp->id,temp->name,temp->grade);
    temp = temp->next;
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.