【问题标题】:fscanf crash while reading to struct in C在 C 中读取结构时 fscanf 崩溃
【发布时间】:2013-04-14 15:35:02
【问题描述】:

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

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

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

提前致谢!

【问题讨论】:

  • 你试过调试器吗?
  • 你应该为你读取的字符串分配内存。

标签: c crash scanf


【解决方案1】:

您无法读取任意内存地址。为学生结构分配内存后,您还需要为每个字符串分配内存。粗略:

    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 ... */;
    }

【讨论】:

  • 有这个想法,但觉得这样做太不切实际了..谢谢。
【解决方案2】:

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

struct student {
    char surname[100];
    char name[100];
    char group[100];
};

【讨论】:

    猜你喜欢
    • 2016-04-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-16
    相关资源
    最近更新 更多