我正在为我的家庭作业开发一些 C 应用程序,但我正面临着恼人的崩溃。这是我的代码:
#include <stdio.h>
#include <stdlib.h>
//Constants
//Available user choices
enum commands {READ_LIST = 1, QUIT};
struct student {
char* surname;
char* name;
char* group;
};
typedef struct student Student;
typedef Student * studentPtr;
//Globals
int studentCount = 0;
//Function declarations
void displayCommands();
void readList();
//Main function
int main() {
char enteredValue[999];
int thisCommand;
int running = 1;
while(running) {
displayCommands();
scanf("%s", enteredValue);
thisCommand = atoi(enteredValue);
puts("\n----------------------------------------------");
switch(thisCommand) {
case READ_LIST:
readList();
break;
case QUIT:
running = 0;
break;
default:
puts("Wrong command!");
break;
}
}
system("pause");
return 0;
}
void displayCommands() {
puts("\n---------------------------------------------");
puts("Enter a command number:");
printf("%d - Read students from file.\n", READ_LIST);
printf("%d - Quit.\n", QUIT);
puts("----------------------------------------------");
}
void readList() {
FILE *fp = NULL;
fp = fopen("studs.txt", "r");
studentPtr newStudentPtr = malloc(sizeof(Student));
if(fp != NULL) {
fscanf(fp, "%d", &studentCount);
if(newStudentPtr != NULL) {
fscanf(fp, "%s %s %s", newStudentPtr->surname,
newStudentPtr->name, newStudentPtr->group);
}
fclose(fp);
} else {
puts("Unable to open file for reading!");
}
}
我基本上尝试将整数蚂蚁三个字符串读入一个结构。程序在尝试读取文件的最后一行时崩溃。
请问有什么帮助吗?我犯了什么错误?
提前致谢!