Reputation: 1373
I've got these prototypes:
int *my_func(int x, void (*other_func)(int a, int b));
int func2(int val1, int val2);
Assume there is a function written that matches it.
If I want to actually call my_func, how would I do it? I've tried the following with no luck:
my_func(1,func2);
Here's the error:
warning: passing argument 2 of ‘my_func’ from incompatible pointer type
Upvotes: 0
Views: 2494
Reputation: 881503
Your original code had void*
for the first argument of the passed function and a return type of int
, and that was causing your issue:
int *my_func(int x, void (*other_func)(void * a, int b)) { return 0;}
int func2(int val1, int val2) {}
int main (void) {
my_func (42, func2);
return 0;
}
With the following edits, changing it to an int
and returning void
, there is no issue:
int my_func(int x, void (*other_func)(int a, int b)) { return 0;}
void func2(int val1, int val2) {}
int main (void) {
my_func (42, func2);
return 0;
}
Compiling the former gives you:
warning: passing argument 2 of 'my_func' from incompatible pointer type
Compiling the latter gives you no errors or warnings and the object file is created fine.
Upvotes: 2
Reputation: 5490
Often(1)(2) we use "typedef" to make sure that the kind of function we have matches the kind of function expected as an argument to the other function.
typedef void (*pt2Func)(void *, int *);
int *my_func(int x, pt2Func other_func);
pt2Func func3;
int main(void){
my_func(1,func3);
}
which means the same thing as
int *my_func(int x, void (*other_func)(void *a, int *b));
void func3(void *val1, int *val2);
int main(void){
my_func(1,func3);
}
Upvotes: 0
Reputation: 471229
That's because the function prototypes don't match:
void (*other_func)(void *a, int *b)
is not the same as:
int func2(int val1, int val2);
One takes a void*
and int*
, while the other takes two int
s.
EDIT:
Also, the return type doesn't match.
EDIT 2:
Since you've fixed both errors, this answer is out of context. I just tested it with these two fixes, and it compiles:
int *my_func(int x, void (*other_func)(int a, int b)){
return 0;
}
void func2(int val1, int val2){
printf("blah");
}
int main(){
my_func(1,func2);
return 0;
}
Upvotes: 5