首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >C语言-结构

C语言-结构
EN

Stack Overflow用户
提问于 2019-01-22 10:18:31
回答 1查看 52关注 0票数 0

当执行第二个fscanf时,控制台停止工作。我做错什么了?

输入文件包含:

代码语言:javascript
运行
复制
3
minsu 50 80 40
sarah 30 60 40
jason 70 80 90

代码:

代码语言:javascript
运行
复制
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>

typedef struct studentT {
    char *name;
    int literature;
    int math;
    int science;
}studentT;

int main()
{
    studentT student[3];
    int count;
    char *inputFileName = malloc(sizeof(char)*30);
    char *outputFileName = malloc(sizeof(char) * 30);
    float avg;
    int i = 0;

    scanf("%s %s", inputFileName, outputFileName);

    FILE *fp = fopen(inputFileName, "r");

    if (fp == NULL)
    {
        printf("file is not exist");
        return 1;
    }

    fscanf(fp, "%d", &count);

    for (i = 0; i < (int)count; i++)
    {
        //printf("!");
        fscanf(fp, "%s %d %d %d", student[i].name, &student[i].literature, &student[i].math, &student[i].science);
        //printf("2");
        printf("%s %d %d %d\n", student[i].name, student[i].literature, student[i].math, student[i].science);
        //printf("333\n");
    }

    fclose(fp);
    free(inputFileName);
    free(outputFileName);
    return 0;

}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-01-22 10:30:53

studentT结构中的name字段是一个char *。您将该指针传递给scanf,而不将其初始化为任何值。所以scanf读取了一个未初始化的指针,并试图取消对它的引用。这会调用未定义的行为。

解决这个问题的最简单方法是将name更改为一个足够大的数组,以容纳您期望的任何字符串。然后,您可以写入数组:

代码语言:javascript
运行
复制
typedef struct studentT {
    char name[20];
    int literature;
    int math;    
    int science;
}studentT;

或者,您可以使用malloc动态分配空间:

代码语言:javascript
运行
复制
student[i].name = malloc(20);
fscanf(fp, "%19s %d %d %d", student[i].name, &student[i].literature, 
                            &student[i].math, &student[i].science);
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/54300354

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档