函数指针数组的⽤途:转移表

举例:计算器的⼀般实现:

我们先实现一下简单的版本

#define _CRT_SECURE_NO_WARNINGS#include int add(int x,int y){return x + y;}int sub(int x, int y){return x - y;}int mul(int x, int y){return x * y;}int div(int x, int y){return x / y;}int main(){int x = 0;int y = 0;int ret = 0;int input = 0;do{printf("*************************\n");printf(" 1:add 2:sub \n");printf(" 3:mul 4:div \n");printf(" 0:exit \n");printf("*************************\n");printf("请选择:");scanf("%d", &input);switch (input){case 0:printf("退出计算机");break;case 1: printf("输入操作数:"); scanf("%d %d", &x, &y);ret = add(x, y); printf("ret = %d\n", ret);break;case 2:printf("输入操作数:");scanf("%d %d", &x, &y);ret = sub(x, y);printf("ret = %d\n", ret);break;case 3:printf("输入操作数:");scanf("%d %d", &x, &y);ret = mul(x, y);printf("ret = %d\n", ret);break;case 4:printf("输入操作数:");scanf("%d %d", &x, &y);ret = div(x, y);printf("ret = %d\n", ret);break;default: printf("选择错误\n");break;}} while (input);return 0;}

可以看出这样的代码繁琐且冗长。

所以我们利用函数指针数组重新实现计算器,代码清晰有条理而且很简单

#define _CRT_SECURE_NO_WARNINGS#include int add(int x,int y){return x + y;}int sub(int x, int y){return x - y;}int mul(int x, int y){return x * y;}int div(int x, int y){return x / y;}int main(){int x = 0;int y = 0;int ret = 0;int input = 1;int(*pfarr[5])(int,int) = { 0,add,sub,mul,div };//函数指针数组 //01 23 4do{printf("*************************\n");printf(" 1:add 2:sub \n");printf(" 3:mul 4:div \n");printf(" 0:exit \n");printf("*************************\n");printf("请选择:");scanf("%d", &input);if (input >= 1 && input <= 4){printf("请输入两个操作数:");scanf("%d %d", &x, &y);int z = pfarr[input](x, y);printf("%d\n", z);}else if (input == 0){printf("退出计算机");}else{printf("输入错误,重新输入\n");}} while (input);return 0;}

然后我们再思考一个问题,第一个代码有很多重复的部分,我们有没有什么办法把这些重复的部分统一表示一下呢?

把函数的指针(地址)作为参数传递给另⼀个函数,当这个指针被⽤来调⽤其所指向的函数时,被调⽤的函数就是回调函数。

完!!!