1

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.

asked Dec 28, 2012 at 15:48
1
  • 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". Commented Dec 28, 2012 at 16:21

2 Answers 2

7

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))()

answered Dec 28, 2012 at 15:52
Sign up to request clarification or add additional context in comments.

2 Comments

Bah, somebody is seriously downvoting this answer? This is uncool. +1.
I've downvoted the answer. I think it should say something about what's wrong with Tom's attempt. Probably say something about how to use calloc, why malloc may be also right, something about the usage of sizeof.. I mean, you just said "use typedef" instead of explaining what he was doing wrong..
2

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)));
answered Dec 28, 2012 at 15:56

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.