这个程序应该操纵一个学生名单。每次我尝试添加多个学生时,都会收到分段错误错误。此外,当我尝试递归打印列表时,出现分段错误。我认为这与我如何保存到结构和/或调用它有关。我对编程很陌生,所以我相信这很简单。有什么想法吗?
//Header file declarations.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
//Structure defintion.
struct student {
int ID;
char name[40];
struct student *next;
};
//Type definition.
typedef struct student Student;
//Function prototypes.
int getChoice();
Student *addToList(Student *List);
void printList(Student *List);
void printListRR(Student *List);
void searchList(Student *List);
/*main function
Objective: This function provides runs a function call based on an option selected the user in another function.
Input: This function recieves no input from the user directly but it is passed their menu selection.
Output: The function outputs error messages and a closing salutation to the user. It returns 0.
*/
int main(void) {
int choice = 0;
Student *SLIST = NULL;
//Call getChoice to get user's selection
choice = getChoice();
//Switch-case for the possible menu selections
while(choice >= 0) {
switch(choice) {
case 0 : printf("Bye...n"); exit(0);
case 1 : SLIST = addToList(SLIST); break;
case 2 : printList(SLIST); break;
case 3 : printListRR(SLIST); break;
case 4 : searchList(SLIST); break;
default: printf("That is not a valid choicen");
}
choice = getChoice();
}
if(SLIST) free(SLIST);
return 0;
}
int getChoice() {
int choice = 0;
printf("n****** MENU ******n");
printf("1. Add new student to list.n");
printf("2. Print the student list, beginning to end.n");
printf("3. Recursively print the student list from the end.n");
printf("4. Search the list for a student.n");
printf("0. Quit.n");
printf("nEnter your choice: ");
scanf("%d", &choice);
return choice;
}
Student *addToList(Student *List){
Student *studentPtr = (Student *) malloc(sizeof(Student));
printf("Student ID: ");
scanf("%d", &(studentPtr->ID));
printf("Student Name: ");
scanf(" %[^n]", studentPtr->name);
if(List == NULL){
return studentPtr;
}
Student *nextStudent = List;
while (nextStudent->next != NULL){
nextStudent = nextStudent->next;
}
nextStudent->next = studentPtr;
return List;
}
void printList(Student *List){
while(List != NULL){
printf("%d %sn", List->ID, List->name);
List = List->next;
}
}
void printListRR(Student *List){
if(List == NULL){
return;
}
printListRR(List->next);
}
void searchList(Student *List){
int idSearch;
printf("Enter student ID to search for: ");
scanf("%d", &idSearch);
while(List != NULL){
if(List->ID == idSearch){
printf("%d %sn", List->ID, List->name);
return;
}
List = List->next;
}
printf("ID %d not found", idSearch);
}
尝试在addToList((中初始化studentPtr->旁边的NULL?