当前位置:网站首页>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
边栏推荐
- grpc的开发详解
- label问题排查:打不开标注好的图像
- Ansible automatic operation and maintenance
- 基金的利润分配与税收
- 软件测试 接口测试 Jmeter 5.5 安装教程
- 十大券商:“推土机行情”再现
- 成为唯一的key
- PROJECT #1 - BUFFER POOL [CMU 15-445645]笔记
- 利用kubernetes中的leader选举机制来完成自己的HA应用
- Still stay up late every day and work overtime to make statements? In fact, you don't know how to make reports efficiently
猜你喜欢

Ansible automatic operation and maintenance
![Project 1 - buffer pool [cmu 15-445645] notes](/img/33/304e3e78f62b156d0863a41d243679.png)
Project 1 - buffer pool [cmu 15-445645] notes

Qt中使用QDomDocument和QDomnode来读取xml

Status acquisition and control system of on-site express cabinet

写论文工具:LaTex在线网站

Open source the Ernie tiny lightweight technology of "Wenxin big model", which is accurate and fast, with full effect
Evolution from stand-alone to distributed database storage system

How can the local / park do a good job in industrial analysis?

2022 PMP project management examination agile knowledge points (5)

微博系统中”微博评论“的高性能高可用计算架构
随机推荐
Does rapid software delivery really need to be at the cost of security?
label問題排查:打不開標注好的圖像
Does rapid software delivery really need to be at the cost of security?
Leetcode 1385. 两个数组间的距离值
Unity Pac Man games, maze implementation
STM32基础知识点
[cooking record] - hot and sour cabbage
Detailed description of gaussdb (DWS) complex and diverse resource load management methods
Gracefully transform the SMS business module and start the strategic mode!
Steady! The best posture for thousands of microservices to access Zadig (helm chart)
InfluxDB时序数据库系统
flutter 插件版本冲突的解决方法
字节云数据库未来方向的探索与实践
Ansible自动化运维
CE第二次作业
0. grpc environment setup
Mysql database: partition
啃下大骨头——排序(一)
Wechat applet: picture seconds plus watermark generation
Deep parsing of kubernetes controller runtime

