using arrays to store function pointers in C language increases the flexibility of function usage. You can invoke different functions simply by providing an array index.
Pre-Knowledge:
1. Pointers to functions
A function is assigned a portal address at compile time, and this address is called a pointer to a function.
For example:
int Max (int,int); Declaring functions, comparing two-number-size int (*p) (); A pointer to a function that declares a variable P=max; Assigns the entry address of the function max to the pointer variable pint c= (*p) (A, b); Calling functions
2. function pointer as function parameter
Each time a different argument (function name) is given to the process function in this example, different functions can be implemented, and the function itself does not have to make any modifications.
#include "stdafx.h" int add (int a,int b) {int sum =a+b;return sum;} int sub (int a,int b) {int sub =a-b;return sub;} int muti (int a,int b) {int muti=a/b;return muti;} int process (int a,int b,int (*fun) (int,int)) {int result = (*fun) (A, B); return result; int main (int argc, char* argv[]) {int Result=0;result =process (8,4,muti);p rintf ("%d \ n", result); return 0;}
3. Array of function pointers
In a menu-driven system, the user can enter an integer value to select a Feature option in the menu. The integer value serves as the subscript for the array of function pointers, and the function pointers in the array can be used to invoke the function.
The following example shows the declaration and use of an array of function pointers. 3 functions are defined in the program: FUNC1, Func2, func3, and each function takes an integer parameter with no return value.
#include "stdafx.h" void func1 (int a) {printf ("choiced: %d \ n", a);} void Func2 (int a) {printf ("choiced: %d \ n", a);} void func3 (int a) {printf ("choiced: %d \ n", a);} int main (int argc, char* argv[]) {int a;void (*f[3]) (int) ={func1,func2,func3};p rintf ("Choice number: \ n"); scanf ("%d", & Amp;a);d o{(*f[a]) (a);p rintf ("Choice number: \ n"); scanf ("%d", &a);} while ((a>=0) && (a<3)); return 0;}
Using arrays to hold function pointers in the "example" C language