Arrays of Pointers to Functions
Understanding Arrays of Pointers to Functions in C
An array of pointers to functions is a construct in C that allows you to store addresses of multiple functions in an array. This enables you to dynamically select and call a specific function at runtime based on the situation or conditions.
Here's an example to help you understand better:
#include <stdio.h>
// Define two functions that we'll use in the array
int add(int a, int b) {
return a + b;
}
int subtract(int a, int b) {
return a - b;
}
int multiply(int a, int b) {
return a * b;
}
int main() {
// Define an array of function pointers
int (*func_ptr[3])(int, int) = {add, subtract, multiply};
// Call the functions using the function pointers
int result_add = func_ptr[0](4, 2); // Calls add(4, 2)
int result_subtract = func_ptr[1](4, 2); // Calls subtract(4, 2)
int result_multiply = func_ptr[2](4, 2); // Calls multiply(4, 2)
printf("Result of add: %d\n", result_add);
printf("Result of subtract: %d\n", result_subtract);
printf("Result of multiply: %d\n", result_multiply);
return 0;
}
In this example, we have three functions (add, subtract, and multiply) that take two integer arguments and return an integer. We then declare an array of function pointers named func_ptr. Each element of this array is a pointer to a function that matches the signature int (*)(int, int) (a function that takes two integers and returns an integer).
We initialize the func_ptr array with the addresses of the three functions add, subtract, and multiply.
In the main function, we use these pointers to call the respective functions. func_ptr[0](4, 2) calls the add function, func_ptr[1](4, 2) calls the subtract function, and func_ptr[2](4, 2) calls the multiply function.
The output of this program will be:
Result of add: 6
Result of subtract: 2
Result of multiply: 8
This demonstrates how an array of pointers to functions can be used to select and execute functions dynamically based on the situation.