i need to write a function that receives an array of pointers to functions. i wrote the following code, however i'm having trouble in testing it at the moment.
is this the correct way to define a pointers to function array?
typedef (*Function)(double);
void func(Function* arr);
and if i want to declare the size of the array with [20] do i write:
void func(Function arr[20]);
?
thanks for your help
First, my usual method for figuring out complex types. Start with the identifier, and then add on the rest one step at a time:
For an array of pointers to functions taking a double parameter and returning a double value, that would be
However, remember that expressions of array type "decay" from type "N-element array of T" to "pointer to T" in most contexts. When you pass an array expression as an argument to a function, what the function actually receives is a pointer. So, instead of receiving an object of type "N-element array of pointer to function returning double", your function will receive an object of type "pointer to pointer to function returning double", or
So your function definition would look something like
And the caller would look something like
If you want to use typedefs instead, you could use something like this:
Using the typedefs makes the array and function parameter look more like regular types. Personally, I prefer using the "raw" types, since it shows explicitly that I'm dealing with pointers to functions, and it shows what the return and parameter types are.
If you correct the typedef to include a return type
typedef void (*Function)(double);
, that array declaration will work fine. You'd call it by calling(arr[index])(3.14)
for the array case.BTW: http://www.newty.de/fpt/fpt.html is a handy reference for function pointers.
What does the function return? You're the return type in the function pointer typedef, like you should have something like
it looks almost correct i think you forgot the return type when declaring Function:
instead
the second declaration is invalid too i think because it is invalid to specify array size for function parameters
will do just fine