当前位置:网站首页>Definition and usage of callback function and qsort function in C language
Definition and usage of callback function and qsort function in C language
2022-07-19 16:07:00 【Never stop】
Callback function :
Functions called through function pointers , If you put a pointer to a function ( Address ) Pass as argument 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 called directly by the function's implementer , It's called by another party when a particular event or condition occurs , Used to respond to the event or condition .
give an example :
#include<stdio.h>
void menu()
{
printf("********************************\n");
printf("** 1.and 2.sub **\n");
printf("** 3.mul 4.div **\n");
printf("********************************\n");
}
int add(int x, int y)
{
int z = 0;
z = x + y;
return z;
}
int sub(int x, int y)
{
int z = 0;
z = x - y;
return z;
}
int mul(int x, int y)
{
int z = 0;
z = x * y;
return z;
}
int div(int x, int y)
{
int z = 0;
z = x / y;
return z;
}
void Calc(int(*pf)(int, int))//int(*pf)(int, int) be equal to add, Just choose different ways to call
{
int x = 0;
int y = 0;
printf(" Please enter two operands :>");
scanf_s("%d%d", &x, &y);
printf("%d\n", pf(x, y));// Through the pointer add Function to call , Instead of using the function name as before
}
int main()
{
int input = 0;
do
{
menu();
printf(" Please select :>");
scanf_s("%d", &input);
switch (input)
{
case 1:
Calc(add);// take add The address of the function is passed , there add The function is a callback function
break;
case 2:
Calc(sub);
case 3:
Calc(mul);
case 4:
Calc(div);
}
} while (input);
}

A pointer to an array of function pointers :
The pointer to the array of function pointers is a pointer , Point to an array , The elements of the array are function pointers ;
How to define ?
int arr[10] = {
0 };// integer array
int(*p)[10] = &arr;// Take the address of the array
int (*pf)(int, int);// A function pointer
int(*pfarr[4])(int, int);//pfarr Is an array , An array of function pointers
int(*(*ppfarr)[4])(int, int) = &pfarr;//ppfarr A pointer to an array of function pointers
//pfarr It's an array pointer , The array that the pointer points to is 4 Elements
// The type of each element of the array pointed to is a function pointer int(*)(int,int)
void*:
An address that can be used to receive any type of data , Alias universal pointer
Since you can store any type of address , Is it possible to dereference and access stored values ?
Let's take an example :
#include<stdio.h>
int main()
{
int a = 10;
void* p = &a;
printf("%d\n", *p);
}
From the output we find that , The program is not running correctly , It's about telling us , We did illegal indirect addressing .
So why does this happen ?
as a result of void* Although you can accept any type of address , But its own type is empty , When dereferencing , The system does not know its type , So I don't know how many bytes need to be allocated , The pointer type determines its byte size .
therefore ,void* Cannot dereference
Then you can ++/– Operation ?
Let's verify it with an example :
#include<stdio.h>
int main()
{
int a = 10;
void* p = &a;
p++;
}
The program still doesn't work correctly , The compiler pointed out the cause of the error :void Unknown size , The same is true of the above , We don't know where it is stored at this time void What kind of data is inside , Naturally, I don't know the size of the memory space it occupies , Therefore, the step length cannot be determined .
therefore void* Nor can it be carried out ++/– operation
qsort(qulick sort)- Library function :
Applicable scenarios : It is suitable for quick sorting of a group of data
qsort(s,sz,sizeof(s[0]),cmp_stu_by_name);
// The first parameter s: The address of the first element of the array to be sorted
// The second parameter sz: Number of elements of the array to be sorted
// The third parameter sizeof(s[0]): The size of each element of the array to be sorted , Unit is byte
// Fourth parameter : It's a function pointer , Compare the address of the function used by the two elements
// The two parameters of the function pointer implemented by the user of this function are : The addresses of the two elements to be compared
give an example :
Conventional methods : Bubble sort :
#include<stdio.h>
int main()
{
int arr[10] = {
9,2,3,1,4,5,7,6,0,91 };
int i, j=0,temp;
int sz = sizeof(arr) / sizeof(arr[0]);
for (i = 0; i < sz-1; i++)// Decide how many times you need to compare
{
for (j=0; j < sz-1-i; j++)
{
if (arr[j+1] > arr[j])
{
temp = arr[j+1];
arr[j+1] = arr[j];
arr[j] = temp;
}
}
}
for (i = 0; i < sz; i++)
{
printf("%d ", arr[i]);
}
return 0;
}
91 9 7 6 5 4 3 2 1 0
however , This method has great limitations , The execution efficiency is not high .
Therefore, when sorting data types , We can choose qsort function :
Now let's learn qsort function :
//int (*cmp)(const void *,const void *);
qsort(*s, n, sizeof(s[0]), cmp);
The first parameter s It's an address , That is, the first address involved in sorting ; n Is the quantity to be sorted ; sizeof(s[0]) Is the space occupied by each element ;
Pointer to function , Used to determine the sort order .
sz=sizeof(arr)/sizeof(arr[0])
qsort(a, sz,arr[0], cmp);
// among cmp The function should be written as :
int cmp(const void *a, const void *b)//void* Any type of data is acceptable
{
return *(int*)a - *(int*)b; // Order from small to large
//return *(int *)b - *(int *)a; Sort from big to small
}
The comparison and implementation process of shaping data :
#include<stdio.h>
#include<stdlib.h>#qsort The header file
int cmp_int(const void* e1, const void* e2)//e1 and e2 Is the address used to receive the two elements to be compared
{
return *(int*)e1 - *(int*)e2;
}
int main()
{
int arr[10] = {
9,8,7,6,5,4,3,2,1,0 };
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]);// Shaping printing %d
}
return 0;
}
0 1 2 3 4 5 6 7 8 9
The comparison and implementation process of floating-point data :
int cmp_float(const void* e1, const void* e2)//e1 and e2 Is the address used to receive the two elements to be compared
// because cmp_float The return type of the function is int, therefore , Need to transform
{
// You can use if Branch statement
/*if (*(float*)e1 == *(float*)e2) return 0; else if (*(float*)e1 > *(float*)e2) return 1; else return 0;*/
// Also available return Go straight back to
return ((int) * (float*)e1 - *(float*)e2);
}
int main()
{
float f[] = {
9.0,8.0,7.0,6.0,5.0,4.0 };
int sz = sizeof(f) / sizeof(f[0]);
qsort(f,sz, sizeof(f[0]), cmp_float);
int i = 0;
for (i = 0; i < sz; i++)
{
printf("%f ", f[i]);// Floating point printing %f
}
return 0;
}
For the implementation process of structure type data :
There is a slight difference between structure type and integer floating-point type in sorting , Structure types cannot be directly compared , But according to a certain variable , for example : name , Age and so on
Compare by age :
#include<stdio.h>
#include<stdlib.h>
struct stu// Define a structure
{
char name[20];
int age;
};
int cmp_s_stu(const void* e1, const void* e2)//e1 and e2 Is the address used to receive the two elements to be compared
{
return ((struct stu*)e1)->age - ((struct stu*)e2)->age;// Tell the compiler how you want to sort
}
int main()
{
struct stu s[3] = {
{
"zhangsan",20},{
"lisi",30},{
"wangwu",10} };
int sz = sizeof(s) / sizeof(s[0]);
qsort(s,sz, sizeof(s[0]), cmp_s_stu);
int i = 0;
for (i = 0; i < sz; i++)
{
printf("%s ", s[i]);# String type , With %s Print
}
return 0;
}
Compare by name :
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
struct stu
{
char name[20];
int age;
};
int cmp_s_stu(const void* e1, const void* e2)//e1 and e2 Is the address used to receive the two elements to be compared
{
return strcmp(((struct stu*)e1)->name,((struct stu*)e2)->name);// Comparing names is comparing strings
// Note that when comparing the size of strings , You can't compare directly with addition and subtraction , And want to use strcmp() function
}
int main()
{
struct stu s[3] = {
{
"zhangsan",20},{
"lisi",30},{
"wangwu",10} };
int sz = sizeof(s) / sizeof(s[0]);
qsort(s,sz, sizeof(s[0]), cmp_s_stu);
int i = 0;
for (i = 0; i < sz; i++)
{
printf("%s ", s[i]);# String type , With %s Print
}
return 0;
}

边栏推荐
- 哈希表相关知识
- Is it safe to open an account with a new bond account? Is it reliable?
- Open source WPF control library adonisui
- JUC源码学习笔记2——AQS共享和Semaphore,CountDownLatch
- WPF效果第一百九十二篇之TreeView支持多选
- [today in history] July 17: Softbank acquired arm; The first email interruption; Wikimedia International Conference
- 阿米的思考
- Interference signal radiated from motor
- HCIA -- OSPF experimental report
- A few lines of code, let black and white old photos regain their vitality!
猜你喜欢

A Ye's new hairstyle

【干货】MySQL底层架构设计,你了解多少?

王者荣耀商城异地多活架构设计

OpenCV-图像透明区裁剪ImageCroppingTRN

Conscience products produced by Tencent? Detailed experience of translation function

Why is Emoji called Emoji

进 /user/用户名/Library/Application Support/

Griddlyjs: Web ide based on Reinforcement Learning

Liquibase学习 - 问题解决:启动报错

解决MATLAB安装后出现 “License Manager Error -8”(亲测有效)
随机推荐
Liquibase learning 1 - installation, simple use
Advanced C language - struct implementation bit segment
关于双网卡配置后只能一个IP访问的问题
Troubleshooting methods of row lock in Oracle
Next stop, embossed AI
Liquibase学习 - 问题解决:启动报错
【单片机仿真项目】报警灯(proteus原理图+keil代码)
Excel文件数据导入到MySQL数据库
Through JMeter pressure measurement surging
几行代码,让黑白老照片重获新生!
[MCU simulation project] advertising lamp (Proteus schematic +keil code)
Use of promise object in ES6 asynchronous programming
Liquibase学习1 - 安装、简单使用
【單片機仿真項目】報警燈(proteus原理圖+keil代碼)
Excel单元格设置下拉选项
Advanced customization of uni app [day13]
C语言之回调函数,qsort函数的定义及使用方法
Try to exercise swimming skills
Codeforce:b. mark the dust sweeper [fill 0 + move]
A few lines of code, let black and white old photos regain their vitality!