0

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.

1
  • alternateName p = &collection[2]; Assuming that this is the same collection as above, you take the address of the third element, which does not exist. Try alternateName p = collection; or alternateName p = &collection[0]; Commented Feb 9, 2022 at 6:23

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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.