c - 将值加载到函数内的结构指针中

标签 c pointers structure function-pointers

所以我只是想将一些值加载到结构中,但无法让它工作。我是 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/

相关文章:

c++ - 在自定义构造函数中的堆上创建指针

php - 显示类别的无限结构 --> 子类别 --> 等等?

c - 类型转换 void 指针并分配内存

c - Fork 子进程以信号 0 终止

c++ - 为什么指向数组表达式的指针起作用

c - C 中的文件 IO 和字符串意外值

c++ - 如何将子类对象添加到其父类的 vector 中 (C++)?

c++ - 构造具有多重继承的类

c - Windows API : Get micro seconds between milli seconds

c - 我在 DbgView 中看不到日志,但在 DeviceTree 中可以看到过滤器