views:

324

answers:

5

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?

A: 

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.

Adam Wright
+4  A: 

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*);
JaredPar
A: 

Can you tell what is the function prototype of map ?

Tanuj
+2  A: 

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

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

DigitalRoss