-1

我正在为我的家庭作业开发一些 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!");
    }
}

我基本上尝试将整数蚂蚁三个字符串读入一个结构。程序在尝试读取文件的最后一行时崩溃。

请问有什么帮助吗?我犯了什么错误?

提前致谢!

4

2 回答 2

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 ... */;
    }
于 2013-04-14T15:37:16.077 回答
1

您可以更改您struct student的包含字符数组(代替字符指针);

struct student {
    char surname[100];
    char name[100];
    char group[100];
};
于 2013-04-14T15:43:17.877 回答