I have an array of function pointer:
int (*collection[2]) (int input1, int input 2) = {&fct1,&fct2}
I can get values by calling both functions from the array:
*collection[0](1,2);
*collection[1](1,2);
Using typedef, I want another way to invoke the array of function pointer. So far, I am doing:
typedef int (*alternameName)(int input1, int input 2);
alternateName p = &collection[2];
int result1 = (*p[0])(1,2);
int result2 = (*p[1])(1,2);
printf("results are: %d, %d",result1, result2);
My issue is I do not think I properly defined the variable p as I keep getting 0 as my results.
CodePudding user response:
It is generally cleaner to typedef function types, not function pointers. It results in cleaner syntax:
typedef int collection_f(int, int);
Now you can define collection
, simply as an array of pointer to collection_f
.
collection_f* collection[2] = {&fct1,&fct2};
A typical call syntax would be:
collection[0](1,2);
collection[1](1,2);
Don't de-reference function pointer prior to calling. Actually, call operator takes a function pointer as an operand, not a function. Functions decay to function pointer in all context except &
operator ... which returns a function pointer.
Next, I'm not sure what:
alternateName p = &collection[2];
is supposed to mean. I assume that you want p
to point to the first element of collection
. Moreover, indexing p[1]
and p[2]
looks like out of bound access because accessing collection is only defined for indices 0 and 1.
Now your code could be rewritten can:
collection_f** p = collection; // pointer to first element which is a pointer to collection_f
int result1 = p[0](1,2);
int result2 = p[1](1,2);
printf("results are: %d, %d",result1, result2);
I hope it fixes the problem.