Function Pointers within structures in C

2019-08-03 18:43发布

问题:

typedef struct Item{

  int i;
  int j;    
  void (*fooprint)(item*);

}item;

void fooprint(item *it){
  printf("%d\n",it.i);
}


int main(){

  item myitem;
  myitem.i=10;
  myitem.j=20;
  myitem.fooprint = fooprint;

  myitem.fooprint(&myitem);
  return 0;
}

This code gives a error at void (footprint)(item). "The error is expected ‘)’ before ‘*’ token ". Am I missing something ? When I do the same without using pointer to the structure is works. Example : void (*footprint)(item)

回答1:

The type item is not known yet when you use it. You can solve that with a forward declaration.

typedef struct Item item;
struct Item {
    int i;
    int j;
    void (*fooprint)(item*);
};

Another possibility is not to use the typedef to define members:

typedef struct Item {
    int i;
    int j;
    void (*fooprint)(struct Item *);
} item;


回答2:

I'm not sure why you're getting the particular error you are -- the error I got was "error: unknown type name ‘item’". This is because the typedef has not "happened" yet, and C doesn't know what the type item refers to. Use struct Item in place of item there.

(Also, it.i in the printf should be it->i).