I want my function to create an array and allocate memory for n pointers to functions (for example, functions that have no parameters and return int) and to return a pointer to that array.
I tried doing:
void* f(int n){
return calloc(int (*arrayName[])(void),n);
}
But i'm getting a syntax error. I'm pretty new to c and i tried to dig for an hour how to solve this issue with no success. using the man page i figured calloc is the way to go but i might be wrong.
-
I'm a tad curious as to why you need to allocate an array of function pointers. Are you creating code on the fly? Or are you building some sort of dynamic programming environment where you chain functions together and execute them one after another. What I'm trying to say is that this "smells like bad code".Mats Petersson– Mats Petersson2012年12月28日 16:21:14 +00:00Commented Dec 28, 2012 at 16:21
2 Answers 2
Make your life easier and use typedefs:
typedef int (*fp)();
fp * f(size_t n)
{
return calloc(n, sizeof(fp));
}
The hand-rolled declaration: int (*f(size_t n))()
2 Comments
Or if you don't want a typedef (hint: you still do want a typedef, just for completeness): wrap the type in a sizeof():
return calloc(n, sizeof(int (*)(void)));