当前位置:网站首页>C pointer advanced 2-- > function pointer array callback function simplifies calculator code, and implements qsort function based on callback function simulation
C pointer advanced 2-- > function pointer array callback function simplifies calculator code, and implements qsort function based on callback function simulation
2022-06-29 23:21:00 【real Wangyanbin】
Advanced pointer
Function pointer array
The function pointer array is an array , Array elements are function pointers .
The form of function pointer array :int (*parr[10])();
parr The first and [] combination , explain parr It's an array , What is the content of the array ?
yes int(*)() Function pointer of type .
Purpose of function pointer array : Transfer table
Example write a calculator :
requirement : There is addition , Subtraction , Multiplication , division .
Our previous code implementation :
#include<stdio.h>
void menu()
{
printf("***************************\n");
printf("****** 1.add 2.sub ******\n");
printf("****** 3.mul 4.div ******\n");
printf("****** 0.exit ******\n");
printf("***************************\n");
}
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 input = 0;
do
{
menu();
printf(" Please select :>");
scanf("%d", &input);
int x = 0;
int y = 0;
int ret = 0;
switch (input)
{
case 1:
printf(" Please enter two operands :>");
scanf("%d %d", &x, &y);
ret = Add(x, y);
printf("%d\n", ret);
break;
case 2:
printf(" Please enter two operands :>");
scanf("%d %d", &x, &y);
ret = Sub(x, y);
printf("%d\n", ret);
break;
case 3:
printf(" Please enter two operands :>");
scanf("%d %d", &x, &y);
ret = Mul(x, y);
printf("%d\n", ret);
break;
case 4:
printf(" Please enter two operands :>");
scanf("%d %d", &x, &y);
ret = Div(x, y);
printf("%d\n", ret);
break;
case 0:
printf(" Exit calculator \n");
break;
default:
printf(" Wrong choice \n");
break;
}
} while (input != 0);
return 0;
}
It is found that the main function of the above code is too cumbersome , There's a lot of repetition .
Every case The blue boxes in the statement are all repeated parts , So how do we use the function pointer array to solve these repeated parts ?
#include<stdio.h>
void menu()
{
printf("***************************\n");
printf("****** 1.add 2.sub ******\n");
printf("****** 3.mul 4.div ******\n");
printf("****** 0.exit ******\n");
printf("***************************\n");
}
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 input = 0;
do
{
menu();
printf(" Please select :>");
scanf("%d", &input);
int x = 0;
int y = 0;
int ret = 0;
int (*arr[5])(int, int) = {
NULL, Add, Sub, Mul, Div };
if (input == 0)
{
printf(" Exit calculator \n");
}
else if(input>0&&input<5)
{
printf(" Please enter two operands :>");
scanf("%d %d", &x, &y);
ret = arr[input](x, y);
printf("%d\n", ret);
}
else
{
printf(" Wrong choice \n");
}
} while (input != 0);
return 0;
}
Callback function
A callback function is a function called through a function pointer . If you put a pointer to a function ( Address ) Pass as a parameter to another
function , When this pointer is used to call the function it points to , Let's just say this is a callback function . The callback function is not controlled by this function
The implementer of directly calls , It's called by another party when a particular event or condition occurs , Used to enter the event or condition
Row response .
Use callback function to simplify calculator
#include<stdio.h>
void menu()
{
printf("***************************\n");
printf("****** 1.add 2.sub ******\n");
printf("****** 3.mul 4.div ******\n");
printf("****** 0.exit ******\n");
printf("***************************\n");
}
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;
}
void calc(int(*pf)(int, int))
{
int x = 0;
int y = 0;
int ret = 0;
printf(" Please enter two operands :>");
scanf("%d %d", &x, &y);
ret = pf(x, y);
printf("%d\n", ret);
}
int main()
{
int input = 0;
do
{
menu();
printf(" Please select :>");
scanf("%d", &input);
switch (input)
{
case 0:
printf(" Exit calculator \n");
break;
case 1:
calc(Add);
break;
case 2:
calc(Sub);
break;
case 3:
calc(Mul);
break;
case 4:
calc(Div);
break;
default:
printf(" Wrong choice \n");
break;
}
} while (input != 0);
return 0;
}
Simulation Implementation Based on callback function qsort function
demonstration qsort Use of functions
qsort - This function can sort any type of data
- void qsort(void* base,// The starting position of the data you want to sort
size_t num,// The number of data elements to be sorted
size_t width,// The size of the data elements to be sorted ( Unit is byte )
int(* cmp)(const void* e1, const void* e2)// A function pointer - Comparison function
);—>MSDN Search for .
The header file -- <stdlib.h>
Sort a set of integer arrays in ascending order
#include<stdio.h>
#include<stdlib.h>
int cmp_int(const void* e1, const void* e2)
{
return (*(int*)e1 - *(int*)e2);
}
int main()
{
int arr[] = {
10,9,8,7,6,5,4,3,2,1 };
int sz = sizeof(arr) / sizeof(arr[0]);
qsort(arr, sz, sizeof(arr[0]), cmp_int);
int i = 0;
for (i = 0; i < sz; i++)
{
printf("%d ", arr[i]);
}
return 0;
}
Use qsort To arrange ascending structure data
#include<stdio.h>
#include<stdlib.h>
int cmp_int(const void* e1, const void* e2)
{
return (*(int*)e1 - *(int*)e2);
}
struct Stu
{
char name[20];
int age;
};
int cmp_stu_by_name(const void* e1, const void* e2)// Compare name
{
return strcmp(((struct Stu*)e1)->name, ((struct Stu*)e2)->name);
}
int cmp_stu_by_age(const void* e1, const void* e2)// Compare age
{
return ((struct Stu*)e1)->age - ((struct Stu*)e2)->age;
}
int main()
{
struct Stu s[] = {
{
"zhangsan", 15}, {
"lisi", 30}, {
"wangwu", 25} };
int sz = sizeof(s) / sizeof(s[0]);
qsort(s, sz, sizeof(s[0]), cmp_stu_by_name);// Yes name Ascending
int i = 0;
for (i = 0; i < sz; i++)
{
printf("%s %d\n", s[i].name, s[i].age);
}
printf("\n");
qsort(s, sz, sizeof(s[0]), cmp_stu_by_age);// Yes age Ascending
for (i = 0; i < sz; i++)
{
printf("%s %d\n", s[i].name, s[i].age);
}
printf("\n");
return 0;
}
With bubble sort simulation qsort function
qsort Function was originally used to sort by quick sort , But quick sorting is learned from data structure , So in C When the language has not learned the data structure, first use the learned bubble sort to simulate .
void bubble_sort(void* base, int sz, int width, int(*cmp)(const void* e1, const void* e2))
{
int i = 0;
for (i = 0; i < sz - 1; i++)
{
int flag = 1;// Suppose the array is ordered
// A bubble sorting process
int j = 0;
for (j = 0; j < sz - 1 - i; j++)
{
if (cmp((char*)base + j * width, (char*)base + (j+1) * width))
{
// In exchange for
Swap((char*)base + j * width, (char*)base + (j+1) * width, width);
flag = 0;
}
}
if (flag == 1)// Judge whether to exchange after a bubble sort , Order without exchange , Exit loop
{
break;
}
}
}
This simulation sqort The difference between the bubble sort function and the previous bubble sort function is (char*)base + j * width, and (char*)base + j * width What does that mean ? Why must I cast to (char*) Well ?
Realization Swap function
void Swap(char* buf1, char* buf2, int sz)
{
int i = 0;
for (i = 0; i < sz; i++)
{
char tmp = *buf1;
*buf1 = *buf2;
*buf2 = tmp;
++buf1;
++buf2;
}
}
The Swap The first and second parameters of the function are the first addresses of the two data to be exchanged .sz Is the size of the two data to be exchanged .
The data of each byte of the two data are exchanged in turn , Finally, the exchange of the two data is completed .
Right up there qsort Several cases of function use ,qsort Function use bubble_sort Function substitution can verify the accuracy of the simulated implementation function in turn
边栏推荐
- Evaluation of powerful and excellent document management software: image management, book management and document management
- 什么是IGMP?IGMP与ICMP有啥区别?
- SQL question brushing 595 Big country
- 深入解析kubernetes controller-runtime
- Gnawing down the big bone - sorting (I)
- Weekly Postgres world news 2022w25
- 啃下大骨头——排序(一)
- flutter 插件版本冲突的解决方法
- pytest初始化和清理环境
- Sword finger offer 38 Arrangement of strings
猜你喜欢

众昂矿业:萤石助力氟产业锂电建设发展

CE第二次作业

Qt中使用QDomDocument和QDomnode来读取xml

Deep parsing of kubernetes controller runtime

什么是IGMP?IGMP与ICMP有啥区别?

Leetcode 1385. 两个数组间的距离值

收藏!这些提高程序员生产力的工具你用过吗?

Qt5.14.2 error connecting to the MySQL database of Ubuntu 20.04

sql刷题595. 大的国家

The soft youth under the blessing of devcloud makes education "smart" in the cloud
随机推荐
sql刷题595. 大的国家
远程沟通高效的自我总结| 社区征文
How ZABBIX 5.0 adds esxi6.7 to monitoring
提供有效的绩效评估
Free PDF to word software sharing, these software must know!
疫情下我离职一年,收入增长了10倍
论文阅读《Large-Scale Direct SLAM with Stereo Cameras》
分布式消息中间件设计
STM32 basic knowledge points
Static keyword continuation, inheritance, rewrite, polymorphism
CE第二次作业
error: C2665: “QMessageBox::critical”: 4 个重载中没有一个可以转换所有参数类型
Laravel 创建自己的 Facade 扩展 geoip 根据 IP 获取国家、地域、城市信息
label问题排查:打不开标注好的图像
C指针进阶2-->函数指针数组 回调函数简化计算器代码,基于回调函数模拟实现qsort函数
Processing of error b6267342 reported by AIX small machine in production environment
Online text digit recognition list summation tool
服务器快速搭建AList集成网盘网站【宝塔面板一键部署AList】
地方/园区如何做好产业分析?
Wechat applet: (update) cloud development wechat group contacts

