Lidbey
Lidbey

Reputation: 371

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

Upvotes: 2

Views: 108

Answers (3)

Petr Skocik
Petr Skocik

Reputation: 60067

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

Upvotes: 1

Cobusve
Cobusve

Reputation: 1570

Looks like your fscanf is passing the value of save->health instead of it's address.

You need to do

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

Since -> has precedence over & this will give you the address of the health member.

Upvotes: 2

0___________
0___________

Reputation: 67713

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

Here you have working verison to play with https://godbolt.org/z/5CuZwR

As in my example always check the result of the scanf

Upvotes: 2

Related Questions