当前位置:网站首页>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
边栏推荐
- Mysql database: the difference between drop, truncate and delete
- wirehark数据分析与取证infiltration.pacapng
- Free PDF to word software sharing, these software must know!
- C language tutorial – -6 loop statement
- 软件测试 接口测试 Postman测试工具 接口测试的流程 执行接口测试 接口关联 环境变量和全局变量 内置动态参数以及自动有的动态参数
- STM32 basic knowledge points
- Node data collection and remote flooding transmission of label information
- 关于二叉树
- grpc的开发详解
- laravel 关联模型 多态关系
猜你喜欢

架构实战营模块 5 作业

剑指 Offer 38. 字符串的排列

软件测试 接口测试 Postman测试工具 接口测试的流程 执行接口测试 接口关联 环境变量和全局变量 内置动态参数以及自动有的动态参数
discrete "digital signal"]"/>Speech signal processing (III): speech signal analysis [continuous "analog signal" -- Sampling, quantization, coding -- > discrete "digital signal"]

正则表达式:字符(2)

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

优雅的改造短信业务模块,策略模式走起!
![The server quickly sets up the alist integrated network disk website [pagoda panel one click deployment of alist]](/img/96/3e634c173c96082881286ba402a067.png)
The server quickly sets up the alist integrated network disk website [pagoda panel one click deployment of alist]

Qdomdocument and qdomnode are used in QT to read XML

收藏!这些提高程序员生产力的工具你用过吗?
随机推荐
C language tutorial – -6 loop statement
label問題排查:打不開標注好的圖像
Mysql database: read write separation
Gnawing down the big bone - sorting (I)
Design of Distributed Message Oriented Middleware
Static keyword continuation, inheritance, rewrite, polymorphism
Regular expressions: characters (2)
Node data collection and remote flooding transmission of label information
Does Australia require that PVC plastic sheets comply with as/nzs 1530.3 with a flame spread index of 0?
微博系统中”微博评论“的高性能高可用计算架构
nrm详解
Talk about auto in MySQL in detail_ What is the function of increment
Free PDF to word software sharing, these software must know!
深入解析kubernetes中的选举机制
采购数智化爆发在即,支出宝“3+2“体系助力企业打造核心竞争优势
Is it safe to open a stock account? Shanghai stock account opening.
Welcome the "top ten" of the Municipal Association for science and technology • pay tribute to Lu Yi, a scientific and technological worker: an explorer guarding the transmission security of the power
数据库-玩转数据-Pgsql 使用UUID做主键
触摸按键与按键控制对应的LED状态翻转
C指针进阶1-->字符指针,数组指针,指针与数组传参,函数指针

