Void * function pointer array cast

I have an array that looks like this:

void* functions[]; // pointer to functions, each function returns an int and has int parameters A and B

I would like to include this in the following:

int (*F)(int a, int b) = ((CAST HERE) functions)[0];
int result = F(a, b);

I already tried "(int (*) (int, int))" as a cast, but the compiler complained that I was trying to use the function pointer as an array.

+4
source share
3 answers

functionis an array of pointers to type data void. You want to pass it to a pointer to pointers of the type int (*)(int, int)that will be int (**)(int, int), so the following works:

int (*F)(int, int) = ((int (**)(int, int)) functions)[0];

As pointed out by @MM , the above will lead to undefined behavior . You might want to read this article for this as well.


Ideally, you would do something like this:

// Array of 2 pointers to functions that return int and takes 2 ints
int (*functions[2])(int, int) = {&foo, &bar};

// a pointer to function
int (*F)(int, int) = functions[0];
int r = F(3, 4);
0

typedef :

typedef int F_type(int, int);

:

F_type *F = (F_type *)(functions[0]);

undefined ( ) functions - , .

, C void * . , :

F_type *functions[] = { &func1, &func2 };

NB. typedef . , , typedefs, , .

+4

(int (**)(int, int)) , Undefined !

void* C.

Note that the overlay is void*on a different type; severe violation of pseudonyms. Read more in What is the effect of dropping a void function pointer?

Please consider using an array of function pointers from the start.

+2
source

Source: https://habr.com/ru/post/1686280/


All Articles