我想显示我的列表,但是,我的print()
函数似乎有问题。请帮帮我!多谢。我试图创建一个具有单个链表的学生管理系统,下面只有 2 个函数将数据输入列表并在插入或删除任何内容之前显示它。据我所知,当我想访问不允许的内存时,会发生分段错误,但它是如此普遍。我需要一些详细的解释和一些解决方案!
#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.%dn",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("ttThe Student Listnn");
printf("%-10s%-40s%-10sn","ID","Name","Grade");
while(temp->next != NULL){
printf("%-10s%-40s%-10dn",temp->id,temp->name,temp->grade);
temp = temp->next;
}
}
int main(){
// head = NULL; //empty list
input();
print();
}
在实现链接列表时,请始终使用笔和纸,并在开始编码之前正确写下每个步骤。编写创建列表、插入新节点、删除节点的每个步骤。不要忘记在创建新节点时将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.%dn",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.%dn",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("ttThe Student Listnn");
while(temp != NULL){
printf("%-10s%-40s%-10dn",temp->id,temp->name,temp->grade);
temp = temp->next;
}
}