Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array of Function-Pointers with different functions return value (in C)

I've seen some examples of array of function-pointers (here, for example)

In the examples I've seen the array holds functions that have a return value of the same type (all int's, or all void's for example).

But I'm wondering can you have an array that holds function-pointers of different types?

The next code won't compile:

#include <stdio.h>

void Empty_Funcion()
{
    ;
}
int funcAdd(int a, int b){
    return a+b;
}

int main()
{
    int ret = 0;

    void *array[5] = {&Empty_Funcion, &funcAdd, &Empty_Funcion, &funcAdd, &Empty_Funcion};

    ret = (*array[1])(5,7);

    printf("%d\n", ret);

    return 0;
}

It says the problem is with the assignment ret =... "void value not ignored as it ought to be".

like image 361
Maverick Meerkat Avatar asked Feb 17 '26 19:02

Maverick Meerkat


1 Answers

You can do it like this:

ret = ( ( int (*)(int,int) ) array[1] )(5,7);

You need to cast to pointer to function type with the correct signature.

like image 70
Anatoly Strashkevich Avatar answered Feb 20 '26 11:02

Anatoly Strashkevich



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!