1. Using a function pointer array to implement the calculator
2. Call the corresponding function by a function pointer variable
#include <stdio.h>int Add (int a,int b) {return a+b;} int sub (int a,int b) {return a-A;} int mul (int a,int b) {return a*b;} int div (int a,int b) {return a/b;} void Make_menu () {printf ("****************************\n");p rintf ("Please select menu: \ n");p rintf ("1: plus 2: minus 3: Multiply 4: except 0: Exit \ n");} /* Define the function pointer array variable (INT,INT) corresponding to the function pointer array to the list of functions */int (*fun_array[4]) (int,int) = {Add, sub, mul, Div}; int main () {int i,j;int cmd;while (1) {make_menu (); scanf ("%d", &cmd); if (cmd==0) {break;} if (cmd>=1&&cmd<=4) {printf ("Please enter 2 numbers:"), scanf ("%d%d", &i,&j);//function pointer array to invoke the corresponding function int result = Fun_array[cmd-1] (I,J); equivalent to int result = (*fun_array[cmd-1]) (I,J);//function pointer variable to invoke the corresponding function//int (*p) (int,int) = Fun_array[cmd-1];//int Result = P (i,j);p rintf ("result:%d\n", result);}} return 0;}
Definition and use of a C function pointer array