所以我只是想将一些值加载到结构中,但无法让它工作。我是 C 新手,指针等仍然有点令人困惑,所以我不太确定为什么这不起作用。
struct monster_{
int health;
int power;
int x_position;
int y_position;
};
void allocate(struct monster_ **a);
void init_monster(struct monster_ *a);
int main(){
struct monster_ *m;
allocate(&m);
init_monster(m);
printf("%d", m->health);
return 0;
}
void allocate(struct monster_ **a){
*a=(void*)malloc(sizeof(struct monster_));
}
void init_monster(struct monster_ *a){
a->health = 100;
a->power = 90;
a->x_position = 25;
a->y_position = 90;
}
所以我想要发生的是 m->health 此时应该打印 100,但它只打印 0。
已编辑:早期的代码实际上并不是我的代码中的内容。这是我实际使用的。
最佳答案
您的代码在我的计算机上按预期工作。我想你需要的只是以下两个头文件:
#include <stdio.h>
#include <stdlib.h>
关于c - 将值加载到函数内的结构指针中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34521881/