gpt4 book ai didi

c - C 中结构的 Malloc

转载 作者:太空宇宙 更新时间:2023-11-04 03:47:47 25 4
gpt4 key购买 nike

所以我必须编写一个 c 程序来读取一个文本文件,将其存储在一个具有额外值(平均值)的结构中,然后将带有 fread 的结构输出到一个新结构中。然而,信息不会去任何地方。我几乎肯定它的 malloc 不知道如何分配适当数量的内存(C++ 和 Java 有点把我宠坏了)

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct student {
int id;
float marks [10];
float gpa;
} Student;

int main (){
FILE *inFile, *bin;
int i, sum, sLength;
char input[45];
char newLine;
inFile = fopen ("Assign6.dat","r");
bin = fopen ("Assign6out.dat","wb+");
Student current;

// while (!feof(inFile)){
sum = 0;
fgets (input,sizeof(input), inFile);
sLength = strlen(input);
sscanf (input, "%d\n", &(current.id));
for (i = 0; i < 6; i++){
sscanf (input, "%lf", &(current.marks[i]));
sum += current.marks[i];
}
current.gpa = sum / 6;
fwrite (&current, sizeof (Student), 1, bin);

// }
fclose(inFile);
Student newer;
fseek (bin, 0, SEEK_SET);
fread (&newer, 1, sizeof(Student), bin);
fclose(bin);
printf( "%d, %.1lf\n", newer.id, newer.marks[0]);
}

所以输入文件是这个

122456 1.0 2.0 3.0 4.0 5.0 6.0

输出是

122456, 0.0

谁能帮我解决这个问题?我环顾四周,但找不到真正适合我的东西。

第一次发帖,请多多关照!

最佳答案

这里的问题很可能是由于undefined behavior引起的: 结构成员 marks 是一个 float 数组,但您尝试使用格式 "%lf" 解析文本文件中的值它需要一个指向 double 的指针。指向 float 的指针与指向 double 的指针不同。

sscanf 格式更改为 "%f",它应该可以更好地工作。

我建议您阅读 this scanf (and family) reference ,它有一个非常好的表格,列出了不同的格式以及他们期望的参数。

关于c - C 中结构的 Malloc,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22988939/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com