c - C语言——结构
问题描述
执行 secondfscanf
时,控制台停止工作。我做错什么了?
输入文件包含:
3
minsu 50 80 40
sarah 30 60 40
jason 70 80 90
编码:
#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;
}
解决方案
结构中的name
字段studentT
是char *
. 您将该指针传递给scanf
而不将其初始化为任何内容。所以scanf
读取一个未初始化的指针并试图取消引用它。这会调用未定义的行为。
name
解决此问题的最简单方法是将数组更改为足够大以容纳您期望的任何字符串。然后你可以写入数组:
typedef struct studentT {
char name[20];
int literature;
int math;
int science;
}studentT;
或者,您可以使用malloc
动态分配空间:
student[i].name = malloc(20);
fscanf(fp, "%19s %d %d %d", student[i].name, &student[i].literature,
&student[i].math, &student[i].science);
推荐阅读
- jquery - jQuery在div中附加一个类不起作用
- php - Facebook PHP SDK 获取页面帖子数据为空
- node.js - 一个函数如何在没有条件检查调用程序/函数的情况下影响其调用者的流程
- java - JTextArea 和 Scanner JAVA 的打字机效果
- netlogo - 分发我的补丁龟,除了那些是集合的一部分
- actions-on-google - Google 模拟器上的 Actions 不接受我的“应用名称”,只有“测试应用”
- data-structures - 有没有类似数据结构的“可逆哈希表”?
- css - Oceanwp 主题的粘滞菜单
- javascript - this.state.query 即使在 this.setState({query:value}) 调用之后也没有设置
- content-management-system - 如何使用 Gravstrap 制作单个站点页面?