繁体   English   中英

将指向结构的指针传递给函数的C问题

[英]C problem with passing pointer to struct to function

我在将结构指针传递给带有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 ,在这个函数完成后我的 health 为零。

我试着像那样做我的功能,它在我改变的功能loadgame()也有相同的解决方案

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

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

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

在这里你可以使用https://godbolt.org/z/5CuZwR

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

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

你需要做

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

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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