简体   繁体   中英

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. 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)

#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]);
}

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 . A pointer to a float is not the same as a pointer to a double .

Change the sscanf format to "%f" and it should work better.

I recommend you read this scanf (and family) reference , it has a very good table of the different formats and what argument they expect.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM