Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C: Passing a function pointer in a function it is passed to

I'm trying to write a mapping function that takes a function pointer, and passes it to another function, but gcc is yelling at me.

Here is an idea of what I'm trying to do.

void map(T thing, void apply(int a, int b, void *cl), void *cl);

void function(T thing, void apply(int a, int b, void *cl), void * cl)
{

   for(int i = 0; i < 10; i++)
   {

      map(thing, apply, cl);

   }

}

gcc's complaint:

warning: passing argument 2 of 'map' from incompatible pointer type

Any ideas?

like image 792
Walker Holahan Avatar asked Feb 05 '26 13:02

Walker Holahan


2 Answers

In order to help with this problem we'd need to see the declaration / signature of the map function. Almost certainly there is a slight difference in the function signature. The easiest way to resolve this is to typedef out a function pointer type and use it in both functions.

typedef void (*apply)(int,int,void*);
like image 122
JaredPar Avatar answered Feb 07 '26 16:02

JaredPar


You can't pass functions around. You need to pass pointers to functions instead.

void map(T thing, void (*apply)(int a, int b, void *cl), void *cl);
void function(T thing, void (*apply)(int a, int b, void *cl), void * cl)
{
    /* ... */
    map(thing, apply, cl);
    /* .... */
}
like image 40
pmg Avatar answered Feb 07 '26 18:02

pmg



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!