我究竟做错了什么?(C编程,指针,结构,函数)

3 c pointers

我不确定我对malloc的使用是否正确,但是让我烦恼的是无法将结构传递给put_age()函数指针.它看起来对我来说,但显然它不是.

#include <stdio.h>
#include <stdlib.h>

typedef struct{
  int age;
  // NPC methods
 int (*put_age)(NPC *character, int age);
} NPC;

////////////////////////////////////

int set_age(NPC *character, int age);

int main(){
  NPC *zelda = malloc(sizeof(NPC));
  zelda->put_age = set_age;
  zelda->put_age(zelda, 25);
  printf("Zelda's age is %d\n", zelda->age);

  return 0;
}

int set_age(NPC *character, int age){
  character->age = age;     
  return 0;
}
Run Code Online (Sandbox Code Playgroud)

编译器输出:

$ gcc ~/test.c
/test.c:7:21: error: expected ‘)’ before ‘*’ token
/test.c:8:1: warning: no semicolon at end of struct or union
/test.c: In function ‘main’:
/test.c:16:8: error: ‘NPC’ has no member named ‘put_age’
/test.c:17:8: error: ‘NPC’ has no member named ‘put_age’
Run Code Online (Sandbox Code Playgroud)

CB *_*ley 16

您的问题是,NPC在声明struct typedef完成之前,这不是类型的名称.你可以通过给结构命名来改变它,例如

typedef struct tagNPC {
  int age;
  // NPC methods
  int (*put_age)(struct tagNPC *character, int age);
} NPC;
Run Code Online (Sandbox Code Playgroud)

要么

typedef struct tagNPC NPC;

struct tagNPC {
  int age;
  // NPC methods
  int (*put_age)(NPC *character, int age);
};
Run Code Online (Sandbox Code Playgroud)