void* function pointer array cast

Viewed 753

I have an array which looks like this:

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

I would like to cast this into the following:

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

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

3 Answers

It will help to use a typedef for the function type:

typedef int F_type(int, int);

Then you can write:

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

It would be undefined behaviour (strict aliasing violation) to try and cast functions to something else before using the index operator.

Note that it is not supported by Standard C to convert void * to be function pointers. If possible, make the array be function pointers in the first place:

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

NB. Some people prefer using a typedef for the function pointer type, instead of the function type. I think it makes for more readable code to avoid pointer typedefs, but I mention this so you can make sense of other suggestions.

Casting with (int (**)(int, int)) might seem to do the trick now, but it invokes Undefined Behavior!

Converting void* to function pointer is not Standard C.

Note that aliasing void* to a different type; a strict aliasing violation. Read more in What is the effect of casting a function pointer void?

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

function is an array of pointers to data of type void. You want to cast it to a pointer to pointers of type int (*)(int, int) which would be int (**)(int, int), so the following works:

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

As pointed out by @M.M, the above will result in undefined behaviour. You might want to read this post and this for more on that.


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);
Related