Search code examples
cfunction-pointersabstract-data-type

C ADT function pointer as parameter?


I have a function in an ADT:

Pgroup new_group(int size, void (*foo)(void *));

In my other class I have this function to send in:

void foo(Pstruc x);

x is a pointer to a struct. When I try to call new_group however, I receive an error "expected 'void (*)(void )' but argument is of type 'void ()(struct struc_ *)". This is how I've been calling it:

Pgroup group = new_group(num, &foo);

Any suggestions?


Solution

  • You can cast the argument to the correct type to get rid of the diagnostic:

    Pgroup group = new_group(num, (void (*)(void *)) foo);
    

    Note that this is not portable as C does not guarantee that the representation between different pointers is the same. The best would be to use types that match in their declarations.