[英]Malloc for struct in C
so I have to do ac program that reads a text file, stores it in a struct with an extra value (the average) and output the struct with fread into a new struct. 因此,我必须做一个读取文本文件的ac程序,将其存储在具有额外值(平均值)的结构中,并将带有fread的结构输出到新结构中。 However the information isnt going anywhere.
但是,信息不会随处可见。 I'm almost positive its the malloc don't know how to allocate the proper amount of memory (C++ and Java kinda spoiled me there)
我几乎是肯定的,它的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 (¤t, 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]);
}
So the input file is this 所以输入文件是这个
122456 1.0 2.0 3.0 4.0 5.0 6.0
and the output is 输出是
122456, 0.0
can anyone help me on this please? 有人可以帮我吗? I looked around but couldn't really find anything that fit for me.
我环顾四周,但找不到真正适合我的东西。
First Post so be nice please! 第一岗,所以请好!
The problem here is most likely due to undefined behavior : The structure member marks
is an array of float
, but you try to parse the values from the text file using the format "%lf"
which expects a pointer to a double
. 这里的问题很可能是由于未定义的行为引起的 :结构成员
marks
是一个float
数组,但是您尝试使用"%lf"
格式解析文本文件中的值,该格式需要一个double
指针。 A pointer to a float
is not the same as a pointer to a double
. 指向
float
的指针与指向double
的指针不同。
Change the sscanf
format to "%f"
and it should work better. 将
sscanf
格式更改为"%f"
,它应该会更好地工作。
I recommend you read this scanf
(and family) reference , it has a very good table of the different formats and what argument they expect. 我建议您阅读此
scanf
(和系列)参考资料 ,它有一个很好的表格,列出了不同的格式以及他们期望的参数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.