我正在为我的作业开发一些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!");
}
}
我基本上尝试将整数ant三个字符串读入结构中。 程序在尝试读取文件的最后一行时崩溃。
请帮忙吗? 我犯了什么错误?
提前致谢!
答案 0 :(得分:4)
您无法读入任意内存地址。将内存分配给学生结构后,还需要为每个字符串分配内存。粗略地:
if(newStudentPtr != NULL) {
char buffer[3][256];
fscanf(fp, "%s %s %s", buffer[0], buffer[1], buffer[2]);
newStudentPtr->surname = malloc(strlen(buffer[0])+1);
strcpy(newStudentPtr->surname, buffer[0]);
newStudentPtr->name = /* similar ... */;
newStudentPtr->group = /* similar ... */;
}
答案 1 :(得分:1)
您可以将struct student
更改为包含字符数组(代替字符指针);
struct student {
char surname[100];
char name[100];
char group[100];
};