C语言 之 理解指针(5)

转移表

本章主要讲的是函数指针数组的用途:转移表

让我们来看看下面的代码:

计算器的一般实现:

复制代码
#include <stdio.h>
int add(int a, int b)
{
	return a + b; //加法函数
}
int sub(int a, int b)
{
	return a - b; //减法函数
}
int mul(int a, int b)
{
	return a * b;//乘法函数
}
int div(int a, int b)
{
	return a / b; //除法函数
}
int main()
{
	int x, y;
	int input = 1;
	int ret = 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 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;
		case 0:
			printf("退出程序\n");
			break;
		default:
			printf("选择错误\n");
			break;
		}
	} while (input);
	return 0;
}

那我们在学习了函数指针数组之后,我们如何改造上面的代码的写法呢?

使用函数指针数组的实现:

复制代码
#include <stdio.h>
int add(int a, int b)
{
	return a + b;
}
int sub(int a, int b)
{
	return a - b;
}
int mul(int a, int b)
{
	return a * b;
}
int div(int a, int b)
{
	return a / b;
}
int main()
{
	int x, y;
	int input = 1;
	int ret = 0;
	int(*p[5])(int x, int y) = { 0, add, sub, mul, div }; //转移表
	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);
		if ((input <= 4 && input >= 1))
		{
			printf("输入操作数:");
			scanf("%d %d", &x, &y);
			ret = (*p[input])(x, y);
			printf("ret = %d\n", ret);
		}
		else if (input == 0)
		{
			printf("退出计算器\n");
		}
		else
		{
			printf("输⼊有误\n");
		}
	} while (input);
	return 0;
}

这就是函数指针数组的使用啦!int(*p[5])(int x, int y) = { 0, add, sub, mul, div }; 创建了一个各个元素为函数指针的数组,这个数组中的函数指针指向特定的函数,所以我们就可以通过下标的访问方式来进行函数的调用了。这个就是转移表。

相关推荐
aramae5 小时前
MySQL复合查询(8)
java·c语言·开发语言·后端·算法
无敌贵点大王5 小时前
RTThread学习记录11——RT-Thread 设备模型吃透:UART/ADC/PWM/PIN 到底有什么区别?
c语言·stm32·学习·链表
Logic1016 小时前
C语言/数据结构位运算题解:异或XOR找出时尚聚会中的“独特颜色“——只出现一次的数字
c语言·数据结构·数组·位运算·时间复杂度·算法题·异或性质
Escalating_xu10 小时前
【C 语言项目】数组和函数综合实践:从零实现控制台扫雷游戏
c语言
Navigator_Z14 小时前
LeetCode //C - 1254. Number of Closed Islands
c语言·算法·leetcode
Logic10114 小时前
C语言/数据结构滑动窗口题解:替换k个字符后的最长连续相同字符子串(LeetCode 424)
c语言·数据结构·字符串·滑动窗口·时间复杂度·频率统计·算法题
free-elcmacom16 小时前
发际线警告!手撕《C陷阱与缺陷》终极 BOSS:signal 函数与 typedef 魔法
c语言·开发语言·visual studio code·visual studio
haluhalu.16 小时前
初识 Protobuf:微服务跨语言通信的一份契约
java·c语言·开发语言·c++·python
临期冰淇淋17 小时前
Unisoc 展锐平台Camera摄像头分辨率适配
linux·c语言·驱动开发
山下梅子酒22517 小时前
洛谷-入门-B2054
c语言