Search code examples
cpointersfunction-pointersvoid-pointerstypecasting-operator

C: How to access a function pointer stored in a void pointer (void *)?


Confused as to how one can access a function pointer stored in a void pointer (void *).


Let's say you have this:

void *functions[] =
{
    &sqrt,         // int ft_sqrt(int nb);
    &power,
    &logN,
    &factorial;
};

// An array of void pointers, each storing a function pointer.

If I wanted to access the sqrt function, my guess would be the following:

(int (*)(int)) functions[0](x)

But my guess is wrong:

error: called object type 'void *' is not a function or function pointer


So how would one access one of these functions ?


Solution

  • It's a matter of operator precedence: The function call operator have higher precedence than the casting operator.

    That means your expression (int (*)(int)) functions[0](x) is really equal to (int (*)(int)) (functions[0](x)).

    You need to explicitly add parentheses in the correct places to cast the pointer: ((int (*)(int)) functions[0])(x).


    A much better solution IMO would be to have an array of pointers to functions, so the array elements already is of the correct type:

    typedef int (*function_ptr)(int);
    
    function_ptr functions[] = { ... };
    

    Then no casting is needed: functions[0](x).

    Then you also would be safe from the issues mentioned in the answer by Lundin.