简体   繁体   中英

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?

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*);

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);
    /* .... */
}

It's just complaining that the function pointer type expected by map 's second argument is different from that of apply . If you either change that type, or (if safe) cast, then it'll be fine.

It works for me with gcc 4.3.3 and -Wall .

While I think all versions of C that ever existed rewrote function "value" parameters to be pointers, you could use a more traditional declaration:

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

But, like I said, your example works fine for me, unchanged except for typedef int T , and map(1, ...)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM