加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-16 10:52:35 所属栏目:百科 来源:网络整理
导读:我不确定我对malloc的使用是否正确,但是让我烦恼的是无法将结构传递给put_age()函数指针.它看起来对我来说,但显然它不是. #include stdio.h#include stdlib.htypedef struct{ int age; // NPC methods int (*put_age)(NPC *character,int age);} NPC;///////
我不确定我对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 %dn",zelda->age);

  return 0;
}

int set_age(NPC *character,int age){
  character->age = age;     
  return 0;
}

编译器输出:

$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’

解决方法

您的问题是,在完成struct typedef的声明之前,NPC不是类型的名称.您可以通过为结构命名,例如,

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

要么

typedef struct tagNPC NPC;

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读