开发者

What am I doing wrong? (C programming, pointers, structs, functions)

I am unsure if my use of malloc is correct, but what bother's me is the inability to pass the struct into the put_age() function pointer. It looks right to me but apparently it isn't.

#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;
}

COMPILER OUTPUT:

$ gcc ~/test.c
/te开发者_如何学Pythonst.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’


Your problem is that NPC isn't the name of a type until the declaration of the struct typedef is complete. You can change this by giving the struct a name, e.g.

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

or

typedef struct tagNPC NPC;

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


I don't think you can use typedef "NPC" inside the struct def. That's because until the compiler has not seen the closing "}" , it has no idea what NPC is.

Please try changing:

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

to:

typedf struct node_npc NPC;

struct node_npc
{
    int age;
    int (*put_age)(NPC *character, int age);
};


Try changing this:

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

To:

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


In set_age(), your variable's name is character, not zelda, so the code should be:

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


I had that problem, when I had a constant defined someware in my code that was named like a member of a struct. Ex.

#define N 10 

struct my_struct{
    int N;
};
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜