当前位置:网站首页>Advanced C language: pointer (3)
Advanced C language: pointer (3)
2022-07-28 23:07:00 【Fishing king chubby】
The authors introduce : Hello everyone , I'm the king of fishing, chubby , You can call me Xiao Du
Author URI : Fishing king chubby personal blog homepage .
The author's gitee: Little bit _ Dudu's individual gitee
Series column : 【 from 0 To 1, roaming c The world of language 】
Xiao Du studies with everyone , Progress together ! Do what you can , Write every blog , Revel in the joy of your progress 🤭. If there are mistakes in the article , Welcome to the comments section ️ correct . Let's start today's study !
Catalog
Preface
Hello everyone ~ Today we will continue to talk about the advanced pointer , This article will lead you to implement a very important function , I hope you will study carefully , Don't talk much , Let's start today's study !
A pointer to an array of function pointers
A pointer to an array of function pointers , It's a pointer , Points to an array of function pointers , The address of the function pointer array is stored in it .
#include<stdio.h>
int main()
{
// Variable name first and [] Combination is array , The first and * Combination is pointer
// A function pointer
int (*pf)(int, int);
// The pointer pf The type is int(*)(int,int); The pointer pf The function type pointed to is int()(int,int)
// Function pointer array
int (*ppf[5])(int, int);
// Array ppf Yes 5 Elements , The type of each element is int(*)(int,int)
// A pointer to an array of function pointers
int (*(*pppf)[5])(int, int);
/* The pointer to the function pointer array is only one more than the function pointer array * The second one * Description is a pointer ,pppf The type of the array of function pointers pointed to is int(* [5])(int,int) This array has 5 Elements , The type of each element is int(*)(int,int) You can also look at it like this , Look at the variable name first pppf, Variable name first and * combination , Description is a pointer , Look out , yes [] Symbol , The pointer points to an array , This array has 5 Elements , The type of each element is int(*)(int,int) Then this array is an array of function pointers . */
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 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 .
Next, we will learn more about the use of callback function through an example
First , Let's first think about bubble sorting , Through the comparison of two adjacent elements, the sorting is finally completed . But bubble sort can only be used for sorting integer arrays .
️ Review bubble sort
Will array arr The elements in are arranged in ascending order
#include<stdio.h>
void bubble_sort(int arr[], int sz)
{
// Number of trips
int i = 0;
for (i = 0; i < sz - 1; i++)
{
// A bubble sorting process
int j = 0;
for (j = 0; j < sz - 1 - i; j++)
{
if (arr[j] > arr[j + 1])
{
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
void print_arr(int arr[], int sz)
{
int i = 0;
for (i = 0; i < sz; i++)
{
printf("%d ", arr[i]);
}
printf("\n");
}
int main()
{
int arr[] = {
9,8,7,6,5,4,3,2,1,0 };
int sz = sizeof(arr) / sizeof(arr[0]);
bubble_sort(arr, sz);
print_arr(arr, sz);
return 0;
}
Effect display :
️ understand qsort Library function
A sort function implemented using the idea of quick sort , This function can sort any type of data ( The default is to arrange in ascending order )
void qsort(void* base,//base The address of the first object in the data to be sorted is stored in
size_t num,// Number of sorted data elements
size_t size,// Sort the size of an element in the data , Unit is byte
int (*compar)(const void*,const void*)// It is used to compare... In the data to be sorted 2 A function of elements
// A function pointer , You can receive different function addresses
//compar: This is a pointer to a comparison function , And the return type of the function pointed to by this function pointer is int, There are two parameters , The type of the parameter is void*
)
Let's take a look at the code :( Ascending )
#include<stdio.h>
#include<stdlib.h>
// The comparison function that compares two integer elements
//e1 Point to an index
//e2 Point to another integer
int int_cmp(const void* e1, const void* e2)
{
return (*(int*)e1 - *(int*)e2);
//e1>e2, The return is >0 Number of numbers , It's in ascending order
//return (*(int*)e2 - *(int*)e1); The return is >0 Number of numbers , It's in descending order
}
void print_arr(int arr[], int sz)
{
int i = 0;
for (i = 0; i < sz; i++)
{
printf("%d ", arr[i]);
}
printf("\n");
}
int main()
{
int arr[] = {
9,8,7,6,5,4,3,2,1,0 };
int sz = sizeof(arr) / sizeof(arr[0]);
qsort(arr, sz,sizeof(arr[0]),int_cmp);
print_arr(arr, sz);
return 0;
}
Effect display :
because qsort It's a library function , So how to sort in this function , This process has been set up , But by observing the function declaration of this function , We know that there must be a place inside this function where the function pointer is called , This is where two elements are compared .
Because the function pointer received the address of the comparison function , So in qsort Inside the function, you can call the comparison function through the function pointer . Just because qsort Functions don't need us to write , We can't see how it is implemented internally .
Now let's focus on the analysis qsort The last argument to the function int ( *cmp )(const void *e1, const void *e2 )
because qsort Function can sort any type of data , When sorting different types of data , The two elements are compared in different ways ( Integer can be used >< To compare , The comparison method of structure types is different )
We need to qsort The function can compare different types of data , That is, we need qsort Functions can be called internally .
therefore ,qsort The function parameter part is a function that can receive different comparisons ( Integer comparison function , Comparison function of structure type ) Function pointer to the address of , such , Through the function pointer, you can call the different objects it points to .
What we have to write ourselves is the comparison function , The return type of this comparison function is int , There are two parameters , The type of the parameter is void* This function only needs to realize the function of comparison .
Return type :
The return type of this function is specified ,e1 Pointing elements >e2 When pointing to an element ( Need to swap ), return >0 Number of numbers ;= when , return 0;< when , return <0 Number of numbers . To do so , The final sorting result is ascending .
And so on , The result I want to return is in descending order , Then I'll let e1 Pointing elements <e2 When pointing to an element ( Need to swap ), return >0 Number of numbers ;= when , return 0;> when , return <0 Number of numbers . To do so , The final sorting result is descending .
Parameters :
e1 Point to the first element to compare ,e2 Point to the second element to compare ,
e1 Is the address of the first element to compare ,e2 Is the address of the second element to compare .
void*:
void* Is a pointer without a specific type , This pointer can receive any type of address
Again because void Is a pointer without a specific type , therefore void Cannot dereference operation , Also can not ± Integers .
Because when I don't know what kind of address it is , I can only use it. void* Type to receive
We said qsort This function can sort any type of data , Let's sort the structure ( The default is ascending )
1. Sort by first name
#include<stdio.h>
#include<stdlib.h>
struct Stu
{
char name[20];
int age;
};
int cmp_Stu_by_name(const void* e1, const void* e2)
{
//strcmp --> >0 ==0 <0
return strcmp(((struct Stu*)e1)->name, ((struct Stu*)e2)->name);
}
int main()
{
struct Stu s[] = {
{
"xiaoming",50},{
"huahua",30} ,{
"wangpeng",40} };
int sz = sizeof(s) / sizeof(s[0]);
qsort(s, sz,sizeof(s[0]),cmp_Stu_by_name);
return 0;
}

2. Sort by age :
#include<stdio.h>
#include<stdlib.h>
struct Stu
{
char name[20];
int age;
};
int cmp_Stu_by_age(const void* e1, const void* e2)
{
//strcmp --> >0 ==0 <0
return ((struct Stu*)e1)->age - ((struct Stu*)e2)->age;;
}
int main()
{
struct Stu s[] = {
{
"xiaoming",50},{
"huahua",30} ,{
"wangpeng",40} };
int sz = sizeof(s) / sizeof(s[0]);
qsort(s, sz,sizeof(s[0]),cmp_Stu_by_age);
return 0;
}

️ Transform the bubble sort function into a similar qsort Function of
What we need to know before transformation :
1、 Why? base The type of this function is void*, because qsort When designing functions , The author did not know that we would use qsort To sort what type of data , So you can't write a specific type , and void* Can receive any type of address , So use void *
2、 When we sort , I must traverse my data , So you need to know the number of elements
3、 We also need to know how many bytes an element is , We already know the starting position and the number of elements , Know how many bytes an element occupies , We can find these elements one by one , Then you can operate on the data
4、 A function pointer , Is to call the function it points to through the function pointer
#include<stdio.h>
void Swap(char* buf1, char* buf2, int width)
{
int i = 0;
for (i = 0; i < width; i++)
{
char tmp = *buf1;
*buf1 = *buf2;
*buf2 = tmp;
buf1++;
buf2++;
}
}
void bubble_sort(void* base, int sum, int width, int (*cmp)(const void* e1, const void* e2))
{
int i = 0;
for (i = 0; i < sum - 1; i++)
{
// Bubble sort
int flag = 1;
int j = 0;
for (j = 0; j < sum - 1 - i; j++)
{
if (cmp((char*)base + j * width, (char*)base + (j + 1) * width) > 0)
{
// In exchange for
// I don't know what kind of data it contains , It's not easy to create temporary variables
// Let's exchange bytes one by one
Swap((char*)base + j * width, (char*)base + (j + 1) * width, width);
flag = 0;
}
}
if (flag == 1)
{
break;
}
}
}
int int_cmp(const void* e1, const void* e2)
{
return (*(int*)e1 - *(int*)e2);
}
void print_arr(int arr[], int sz)
{
int i = 0;
for (i = 0; i < sz; i++)
{
printf("%d ", arr[i]);
}
printf("\n");
}
int main()
{
int arr[] = {
9,8,7,6,5,4,3,2,1,0 };
int sz = sizeof(arr) / sizeof(arr[0]);
bubble_sort(arr, sz, sizeof(arr[0]), int_cmp);
print_arr(arr, sz);
return 0;
}
Effect display :
边栏推荐
- LTE cell search process and sch/bch design
- xshell7,xftp7个人免费版官方下载,无需破解,免激活,下载即可使用
- 《Robust and Communication-Efficient Federated Learning From Non-i.i.d. Data》论文阅读
- 递归和迭代
- Improvement 16 of yolov5: replace backbone network C3 with lightweight network pp-lcnet
- 【滤波跟踪】基于EKF、时差和频差定位实现目标跟踪附matlab代码
- 业界首创云原生安全检测双模型!安全狗重磅报告亮相数字中国建设峰会
- NPM run dev, automatically open the browser after running the project
- 【物理应用】水下浮动风力涡轮机的尾流诱导动态模拟风场附matlab代码
- 18张图,直观理解神经网络、流形和拓扑
猜你喜欢

Reading of "robust and communication efficient federated learning from non-i.i.d. data"

记录一下关于三角函数交换积分次序的一道题

无代码开发平台管理后台入门教程

安全狗入选《云安全全景图2.0》多个细项

Target detection notes -yolo

Sqlilabs-3 (entry notes)

Console.log() console display... Solution

console.log()控制台显示...解决办法

Sqlilabs-1 (breakthrough record)
![[physical application] Wake induced dynamic simulation of underwater floating wind turbine wind field with matlab code](/img/31/e4cd4c261a7fc5cfa731976314530b.png)
[physical application] Wake induced dynamic simulation of underwater floating wind turbine wind field with matlab code
随机推荐
The tenth improvement of yolov5: the loss function is improved to Siou
MySQL Basics - Introduction and basic instructions
shell脚本基础——Shell运行原理+变量、数组定义
LTE cell search process and sch/bch design
安全狗入选《云安全全景图2.0》多个细项
2020年国内十大IC设计企业曝光!这五大产业挑战仍有待突破!
《MySQL数据库进阶实战》读后感(SQL 小虚竹)
Es learning directory
Improvement 11 of yolov5: replace backbone network C3 with lightweight network mobilenetv3
[filter tracking] target tracking based on EKF, TDOA and frequency difference positioning with matlab code
A new MPLS note from quigo, which must be read when taking the IE exam ---- quigo of Shangwen network
Anaconda environment installation skimage package
TypeError: can‘t convert cuda:0 device type tensor to numpy. Use Tensor. cpu() to copy the tensor to
递归和迭代
pg_ Installation and use of RMAN "PostgreSQL"
No code development platform address book tutorial
Sqlilabs-1 (breakthrough record)
Improvement 14 of yolov5: replace the backbone network C3 with the lightweight network GhostNet
Summary of core functions of software testing tool Fiddler postman JMeter charlse
弹框遮罩层「建议收藏」