You almost certainly do not want to allocate an array of functions pointers dynamically. Bad idea.
If you insist, then first of you must realize that malloc always returns an object pointer of type void*
, which is incompatible with function pointers. As is your current senseless cast to int*
. So you need to go to some well-defined middle ground in between function pointers and object pointers, like a uintptr_t
integer.
It is getting tedious to over and over again tell people to use typedef
when working with function pointers, so I'm not gonna do that yet again. This will be messy even with such a typedef
.
Given typedef int func_t (int);
, an array of function pointers is func_t* arr[2];
. However, since you use malloc, you actually need to use a pointer to such an array: func_t* (*funptr)[2]
.
The malloc call will be malloc(sizeof(func_t*[2]))
. However, as mentioned you need to cast the result into something that isn't an object pointer and pray that it's still portable: (uintptr_t)malloc(sizeof(func_t*[2]));
. This is the least questionable I can come up with.
Then you must cast that one to a pointer to array of function pointer type. (func_t*(*)[2])
.
The abomination end result:
typedef int func_t (int);
int main (void)
{
func_t* (*funptr)[2] = (func_t*(*)[2]) (uintptr_t)malloc(sizeof(func_t*[2]));
(*funptr)[0](1);
(*funptr)[1](1);
free(funptr);
}