【问题标题】:in C, a variable doesn't retain the value i assign it and goes back to 0 [closed]在 C 中,变量不保留我分配给它的值并返回 0 [关闭]
【发布时间】:2019-01-29 07:19:33
【问题描述】:

我正在用 C 语言编写一个简单的游戏引擎,但遇到了一个非常奇怪的问题。

//SANJI
objs[1].animation = 1;
objs[1].pho.h = 52;
objs[1].pho.w = 25;
objs[1].pho.tmp_pos.x = 190;
objs[1].pho.tmp_pos.y = 40;
objs[1].pho.gravity = 1;
objs[1].hp = 10;

printf("%d\n", objs[1].hp);//outputs 0???????

似乎无论我做什么,变量(成员)hp 都拒绝接受分配并返回到0。我尝试用谷歌搜索,但恐怕我无法准确地表达这个问题。

编辑: 这是 OBJ 结构的定义:

struct OBJ{
//animation
char animation;//if true apply animation; experimetnal

MOVIE   sprites;
PHYSOBJ pho;

//OBJ_STATE state;
OBJ_STATE states[SEQ_MAX][ST_MAX];
int img;//number of image


int hp;

//control; AI or human
char control;//0 human, otherwise AI
};

printf 和 objs[1].hp = 10 之间也没有代码;我把 printf 放在那里进行测试

【问题讨论】:

  • hpobjs[1].hp 是两个不同的东西。看到minimal reproducible example 会有所帮助。
  • 至少,请发布您定义“objs”结构的代码。这将告诉我们 hp 是如何定义的,以及它与 obj 的关系。但是最好有一个完整的例子:stackoverflow.com/help/mcve
  • 需要看看你是如何定义“objs”的,你确定“%d”是正确的吗?
  • 这个完整的示例:ideone.com/DqW1j1 工作正常,因此如果没有您的帮助,我们无法查看或复制代码中的某些内容。
  • @user3629249: objs[1].animation = 1; 很好。此外,C 无法编写单字节整数文字,因此您必须让编译器进行 int 到 char 的转换..

标签: c game-engine allegro


【解决方案1】:

以下建议的代码:

  1. 演示(通常)如何编写函数
  2. 干净编译
  3. 执行所需的功能

现在建议的代码:

#include <stdio.h>

struct POS
{
    int x;
    int y;
};


struct PHO
{
    int h;
    int w;
    struct POS tmp_pos;
    int gravity;
};
typedef struct PHO PHYSOBJ;


struct OBJ
{
    //animation
    char animation;//if true apply animation; experimetnal

    //MOVIE   sprites;
    PHYSOBJ pho;

    //OBJ_STATE state;
    //OBJ_STATE states[SEQ_MAX][ST_MAX];
    int img;//number of image


    int hp;

    //control; AI or human
    char control;//0 human, otherwise AI
};


int main( void )
{
    struct OBJ objs[2];

    objs[1].animation = 1;
    objs[1].pho.h = 52;
    objs[1].pho.w = 25;
    objs[1].pho.tmp_pos.x = 190;
    objs[1].pho.tmp_pos.y = 40;
    objs[1].pho.gravity = 1;
    objs[1].hp = 10;

    printf("%d\n", objs[1].hp);//outputs 0???????

    return 0;
}

编译、链接、运行时,输出如下:

10

所以问题出在你没有向我们展示的东西上。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-05-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-23
    相关资源
    最近更新 更多