Search code examples
cfunction-pointersansi-c

ANSI C - Functions as Arguments to Other Functions


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

Solution

  • 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 ints.

    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;
    }