我想显示我的列表,但是,我的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();
}
答案 0 :(得分: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;
}
}