1
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)

2 Answers 2

7

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;
Sign up to request clarification or add additional context in comments.

3 Comments

That's what I was thinking, and it through me off when he said it works when he leaves the asterisk off.
Now, the warning I have is :"useless storage class specifier in empty declaration"
Yeah, it doesn't recognise item as a type (because it's not defined yet). Your compiler thinks here that it is a storage declaration (usually auto, register, ...) for an empty type. But that's just an implementation detail of your compiler. My compiler (clang) outputs error: a parameter list without types is only allowed in a function definition
5

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).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.