0
このプログラムは学生リストを操作することになっています。複数の学生を追加しようとするたびに、私はセグメンテーションフォールトエラーが発生します。また、リストを再帰的に印刷しようとすると、セグメント化エラーが発生します。私はそれが私がどのように構造物に保存されているか、そして/またはそれを呼び出すことと関係していると思います。私は非常にプログラミングに新しいので、私はそれが何か簡単だと確信しています。何か案は?ポインタと構造体によるセグメント化エラー
//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 choice\n");
}
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 %s\n", 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 %s\n", List->ID, List->name);
return;
}
List = List->next;
}
printf("ID %d not found", idSearch);
}
プログラムを '-g'オプションでコンパイルし、デバッガで実行します。プログラムがクラッシュすると、デバッガはクラッシュの原因となったコード行を教えてくれます。クラッシュの瞬間にすべての変数の値を調べることもできます。うまくいけば、この情報はあなたの質問に答えるのに役立ちます。 – DyZ
新しいリストエントリを作成するとき( 'malloc'を介して)' next'要素を 'NULL'に初期化する必要があります。 –
IOW、あなたの学生名の(チェックされていない)scanfのあとに 'studentPtr-> next = NULL;'を入れてください。 – WhozCraig