【问题标题】:C problem with passing pointer to struct to function将指向结构的指针传递给函数的C问题
【发布时间】:2020-04-25 05:23:18
【问题描述】:

我在将结构指针传递给带有fscanf() 的函数时遇到问题。

这是我的结构:

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

main我有:

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

我的函数loadgame() 看起来像这样:

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

我的savegame.txt 文件有一行:

health= 5

我的功能不会改变save->health,在这个功能完成后我的健康为零。

我尝试这样做我的功能,它在功能loadgame()中也有相同的解决方案我改变了

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

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

【问题讨论】:

  • 我也尝试传递一个正常的结构(保存保存)和加载游戏(保存),它也不起作用,关键是我试图改变我的结构的值功能
  • //抱歉线程名错误,刚刚改了

标签: c pointers scanf structure


【解决方案1】:

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

在这里,您可以使用 https://godbolt.org/z/5CuZwR 玩的工作版本

在我的示例中总是检查scanf的结果

【讨论】:

    【解决方案2】:

    看起来你的 fscanf 正在传递 save->health 的值而不是它的地址。

    你需要做的

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

    Since -> 优先于 & 这将为您提供健康成员的地址。

    【讨论】:

      【解决方案3】:

      fscanf 需要一个指针,以便知道将值保存在哪里。 除此之外,您的代码还有许多其他小问题。 我已经在下面的 cmets 中解决了这些问题:

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

      【讨论】:

      • @P__J__ 只是坚持我认为可以的 OP 风格。但是可以,为什么不呢。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-07-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-02
      • 2017-01-22
      • 1970-01-01
      相关资源
      最近更新 更多