Search code examples
cpointersscanfstructure

C problem with passing pointer to struct to function


I have a problem passing structure pointer to a function with fscanf().

Here's my struct:

typedef struct {
  int health;
  int y;
  int z;
} save;

in main I have:

save save = { 0 }; //init with zeros
loadgame(&save);
health = save.health;

and my function loadgame() looks like that:

bool loadgame(save* save) {
  FILE* fptr;
  fptr = fopen("savegame.txt", "r");
  if (fptr == NULL)
    return 0;
  fscanf(fptr, "health= %d", save->health);
  return 1;
};

my savegame.txt file has line:

health= 5

and my function doesn't change save->health, after finish of this function my health equals zero.

I tried to do my function like that and it also has the same solution in function loadgame() I changed

fscanf(fptr, "health= %d", save-health);

to

fscanf(fptr, "health= %d", &(save-health));

Solution

  • fscanf needs a pointer so it knows where to save the value. Other than that your code has a bunch of other small issues. I have addressed those in the comments below:

    #include <stdio.h>
    #include <stdbool.h>
    typedef struct {
        int health;
        int y;
        int z;
    }save_tp;
    
    //using the same name for a typedef and a variable is a bad idea;
    //typedef struct{...} foo; foo foo; prevents you from declaring other varibles of type foo
    //as the foo variable overshadows the foo typedef name;
    //better give types a distinct name
    
    
    bool loadgame(save_tp* save){
        FILE* fptr;
        fptr = fopen("savegame.txt", "r");
        if (fptr == NULL)
            return false;
        bool r = (1==fscanf(fptr, "health= %d", &save->health)); //needs an address + may fail
        fclose(fptr); //need to close the file or you'd be leaking a file handle
        return r;
    } //shouldn't have a semicolon here
    
    int main(void)
    {
        save_tp save={0};
        if (!loadgame(&save)) perror("nok");
        else printf("ok, health=%d\n", save.health);
    }