How can I use an array of function pointers?
c, function-pointers, initialization
Solution
You have a good example here (Array of Function pointers), with the syntax detailed.
int sum(int a, int b);
int subtract(int a, int b);
int mul(int a, int b);
int div(int a, int b);
int (*p[4]) (int x, int y);
int main(void)
{
int result;
int i, j, op;
p[0] = sum; /* address of sum() */
p[1] = subtract; /* address of subtract() */
p[2] = mul; /* address of mul() */
p[3] = div; /* address of div() */
[...]
To call one of those function pointers:
result = (*p[op]) (i, j); // op being the index of one of the four functions
You can also initialize `p` as:
int (*p[4]) (int, int) = {sum, subtract, mul, div};
As in:
#include <stdio.h>
// Function declarations
int sum(int a, int b) { return a + b; }
int subtract(int a, int b) { return a - b; }
int mul(int a, int b) { return a * b; }
int div(int a, int b) { return (b != 0) ? a / b : 0; }
int main() {
// Array of function pointers initialization
int (*p[4]) (int, int) = {sum, subtract, mul, div};
// Using the function pointers
int result;
int i = 20, j = 5, op;
for (op = 0; op < 4; op++) {
result = p[op](i, j);
printf("Result: %d\n", result);
}
return 0;
}
As note by Gauthier in the comments
You can call functions by a pointer without dereferencing it.
Some might argue that they want the dereference to be explicit, so they know what they're dealing with. Others would reply that it's a known idiom, and that there isn't much more that `p[op]()` could ever mean.
`result = p[op](i, j);` works
Daniel Heimgartner confirms in the comments:
Initializing the array of pointers `p[0] = sum` and `p[0] = &sum` are equivalent. Similarly, when calling a function (via a function pointer) you do not need to dereference `(*)` it: See this Stack Overflow question "How come a pointer to a function be called without dereferencing?"
Problem
How should I use array of function pointers in C? How can I initialize them?