Search code examples
cfunctionpointersfunction-pointers

Why is there an error while declaring a generic pointer to a function?


While executing this code I get [Error] cast specifies function type at line ptr = (void* (void*, void*))sumx;

I am trying to declare a generic pointer ptr to a function called sumx

Any help would be appreciated. Thank you.

# include <stdio.h>

int sum(int a, int b) {
    return a+b;
}

int* sumx(int *a, int *b) {
    int *p;
    *p = *a+*b;
    return p;
}

int main() {
    int (*p) (int, int);
    void* (*ptr)(void*, void*);

    p = sum;
    ptr = (void* (void*, void*))sumx;


    int s = (*p)(5, 6);

    int a = 10;
    int b = 20;
    int *y = (*ptr)(&a, &b);

    printf("%d\n", s);
    printf("%d\n", *y);
    return 0;
}

Solution

  • You are missing a (*) in the cast, which should be this:

    ptr = ( void* (*)(void*, void*) )sumx;
    

    However, when using such function pointers, it is generally a lot clearer to use typedef statements:

    #include <stdio.h>
    #include <stdlib.h>
    
    int sum(int a, int b)
    {
        return a + b;
    }
    
    int* sumx(int* a, int* b)
    {
        int* p = malloc(sizeof(int)); // Need to allocate some memory
        *p = *a + *b;
        return p;
    }
    
    typedef int (*ifncptr)(int, int);
    typedef void* (*vpfncptr)(void*, void*);
    
    int main()
    {
        ifncptr p;
        vpfncptr ptr;
        p = sum;
        ptr = (vpfncptr)sumx;
    
        int s = p(5, 6); // You can just use the fn-ptr for this call ...
    
        int a = 10;
        int b = 20;
        int* y = ptr(&a, &b); // ^ ... and here, also!
    
        printf("%d\n", s);
        printf("%d\n", *y);
        free(y); // Don't forget to free the memory.
        return 0;
    }