当前位置:网站首页>Detailed pointer advanced 2
Detailed pointer advanced 2
2022-07-03 15:23:00 【Little snail rushes towards】
Preface
Take the book back , Let's continue to explain the pointer , Next, let's start with function pointers .
One A function pointer
First, let's see the following code :

From this we can see that the function name is the address of the function , But how about storing the address of the function ?
We all know that pointers are used to store addresses , So for the address of the function , How will the pointer write .
Writing of function pointer
Return type of function (* Function name )( The parameter type of the function )
#include<stdio.h>
int Add(int x, int y)
{
return x + y;
}
int main()
{
int (*Add)(int, int) = &Add;
return 0;
}For the function Add We need to save its address , You need function pointers , The function pointer above , The return type of the function is int The argument type of the function is int .
We know what function pointers are. Here are two interesting pieces of code :
// Code 1
(*(void (*)())0)();
// Code 2
void (*signal(int , void(*)(int)))(int);
I believe you are a little afraid when you see this code , A face of meng .

Now I'll dissect this code for you .
Code 1
Get this code , We start with our familiar places ,( )0, What is this ? This is just 0 Cast what type , OK, let's continue to see ((void (*)()) Inside void (*)() We are quite familiar with this , This is not a function pointer , So we will 0 Cast to function pointer type ;(*)() This is just a function call , Then this code can be understood as :
Code 1 For a function call , It's called 0 As a function at the address .
hold 0 Cast type to : No arguments , The return type is void The address of the function ;
call 0 The function at the address
Code 2
We continue to analyze from familiar places ,signal function There are two parameters int and void(*)(int) This is the function pointer , So there's still void(*)(int), So we can easily see that this is a function pointer
So the code 2 It can be understood as :
The above is a function declaration ,
Declare the function signal The type of the first argument to the function is int, The type of the second parameter is the function pointer ;
The return type is void,signal The return type of a function is also a function pointer .
In fact, for code 2 We can also simplify .
We can give void(*)(int) Name it puf:
typedef void(*puf)(int);
puf signal(int ,puf)l
Two Function pointer array
What we know is that a function pointer is a function , It is used to store the function address , So what is a function pointer array ?
We can know the function pointer array , The essence of It's an array , The function of this array is to store , Function pointer .
Definition of function pointer array :
data type (* Function name [ Element number ])()
Now let's write a calculator to understand the usage of function pointer array .
Common method :
// Transfer table
#include<stdio.h>
void menu()
{
printf("*************************\n");
printf("***** 1.Add 2.sub *****\n");
printf("***** 3.mul 4.div *****\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;
int x = 0;
int y = 0;
printf(" Please select :\n");
menu();
scanf("%d", &input);
switch (input)
{
case 1:
printf(" Please input the operation :\n");
scanf("%d%d", &x, &y);
int ret = Add(x, y);// Call the add function
printf("sum = %d\n", ret);
break;
case 2:
printf(" Please input the operation :\n");
scanf("%d%d", &x, &y);
ret = sub(x, y);// Call the subtraction function
printf("sum = %d\n", ret);
break;
case 3:
printf(" Please input the operation :\n");
scanf("%d%d", &x, &y);
ret = mul(x, y);// Call multiplication function
printf("sum = %d\n", ret);
break;
case 4:
printf(" Please input the operation :\n");
scanf("%d%d", &x, &y);
ret = div(x, y);// Call the subtraction function
printf("sum = %d\n", ret);
break;
}
return 0;
}Although we have written the transfer table in the conventional way , But in switch There is a lot of redundant code in the statement .
So we can improve :
#include<stdio.h>
void menu()
{
printf("*************************\n");
printf("***** 1.Add 2.sub *****\n");
printf("***** 3.mul 4.div *****\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 = 1;
int x = 0;
int y = 0;
int(*p[5])(int x, int y) = { 0,Add,sub,mul,div };// Transfer table
int ret = 0;
while (input)
{
printf(" Please select :\n");
menu();
scanf("%d", &input);
if (input >= 1 && input <= 4)
{
printf(" Please enter two operands \n");
scanf("%d%d", &x, &y);
ret = (*p[input])(x, y);// Function call
printf("ret = %d\n", ret);
}
}
return 0;
}Here we cleverly borrow function pointer array , Store the first address of the function called by the calculator in the array , This can effectively avoid redundant code .
summary
Purpose of function pointer array : Transfer table
3、 ... and A pointer to an array of function pointers
First of all, yes The pointer , The pointer Point to one Array , The elements of an array are A function pointer .
Definition of a pointer to an array of function pointers :
void test(const char* str)
{
printf("%s\n", str);
}
int main()
{
// A function pointer pfun
void (*pfun)(const char*) = test;
// An array of function pointers pfunArr
void (*pfunArr[5])(const char* str);
pfunArr[0] = test;
// Pointer to function array pfunArr The pointer to ppfunArr
void (*(*ppfunArr)[5])(const char*) = &pfunArr;
return 0;
}There is also an array of pointers to the array of function pointers , Pointer array pointer to function pointer array ,,, There is no need to discuss it next , The understanding ideas are similar to those above .
Four Callback function
Callback function It's a pass through The function called by the function pointer . If you put Pointer to function ( Address ) As Parameters Pass to the other one function , When this The pointer By Used to call the function it points to when , Let's just say this is 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 respond to the event or condition .
In order to deepen the understanding of callback functions , We will simulate the implementation qorst function .
qsort The function is C Language provides a library function , It is used for quick sorting .

qsort Yes 4 Parameters :
base: The starting address of the element to be sorted
mum: Number of elements to sort
witdth: The size of each element ( byte )
cmp: Comparison function
qsort Function implements a quick sorting algorithm , Used to deal with num Element array to sort , The width of each element is bytes . The parameter base is a pointer to the base of the array to be sorted .qsort Overwrite this array with sorted elements . Parameters compare Is a pointer to a user supplied routine , This routine compares two array elements and returns a value that specifies their relationship .qsort Call in sorting process compare Routine one or more times , Pass the pointer to two array elements each time you call
Careful friends may see void * It's something we haven't seen .
void*
Is a pointer without a specific type , This pointer can be followed by a type of address .
notes :void* Cannot be *( Dereference operation ), Also can not +- Integers .
qsort Usage example :
#include<stdio.h>
#include<stdlib.h>
int int_cmp(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,0 };
int sz = sizeof(arr) / sizeof(arr[0]);
qsort(arr, sz, sizeof(arr[0]), int_cmp);
int i = 0;
for (i = 0;i < sz;i++)
{
printf("%d ", arr[i]);
}
return 0;
}Here we note that the comparison function should be written by ourselves , Compare the return value of the function :

The array is sorted in ascending order , As defined by the comparison function . To sort the array in descending order , Please reverse... In the comparison function “ Greater than ” and “ Less than ” The meaning of .
imitation qsort The function realizes a general bubble sorting
void swap(char* buf1, char* buf2, int width)
{
int i = 0;
// Exchange characters one-to-one
for (i = 0;i < width;i++)
{
char tmp = *buf1;
*buf1 = *buf2;
*buf2 = tmp;
*buf1++;
*buf2++;
}
}
// Simulation Implementation qsort
void doubble_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 j = 0;
int flag = 1;// Suppose the array is already in order
for (j = 0;j < sz - 1 - i;j++)
{
if (cmp((char*)base + j * width, (char*)base + (j + 1) * width) > 0)
{
swap((char*)base + j * width, (char*)base + (j + 1) * width, width);// In exchange for
flag = 0;
}
}
if (flag == 1)
{
break;
}
}
}We use function pointers cmp I called the function swap, So the function swap It's a callback function .
summary
After reading this blog , You should know A function pointer yes The pointer , The address used to store the function , about Function pointer array yes Array , Each element in the array is a function pointer , And A pointer to an array of function pointers , Pointer to array , Each element in the array is a function pointer , Callback function It refers to the function called through the function pointer .

边栏推荐
- 视觉上位系统设计开发(halcon-winform)-1.流程节点设计
- Digital image processing -- popular understanding of corrosion and expansion
- Dataframe returns the whole row according to the value
- 高并发下之redis锁优化实战
- What are the composite types of Blackhorse Clickhouse, an OLAP database recognized in the industry
- Puppet自动化运维排错案例
- Apache ant extension tutorial
- 使用Tengine解决负载均衡的Session问题
- Using TCL (tool command language) to manage Tornado (for VxWorks) can start the project
- [attention mechanism] [first vit] Detr, end to end object detection with transformers the main components of the network are CNN and transformer
猜你喜欢

Halcon and WinForm study section 2

基础SQL教程

Digital image processing -- popular understanding of corrosion and expansion

Functional modules and application scenarios covered by the productization of user portraits

高并发下之redis锁优化实战

Chapter 04_ Logical architecture
![[transform] [practice] use pytoch's torch nn. Multiheadattention to realize self attention](/img/94/a9c7010fe9f14454469609ac4dd871.png)
[transform] [practice] use pytoch's torch nn. Multiheadattention to realize self attention

【云原生训练营】模块七 Kubernetes 控制平面组件:调度器与控制器

【云原生训练营】模块八 Kubernetes 生命周期管理和服务发现

秒杀系统3-商品列表和商品详情
随机推荐
Leetcode the smallest number of the rotation array of the offer of the sword (11)
Visual upper system design and development (Halcon WinForm) -4 Communication management
使用JMeter对WebService进行压力测试
Redis single thread problem forced sorting layman literacy
从 flask 服务端代码自动生成客户端代码 -- flask-native-stubs 库介绍
Digital image processing -- popular understanding of corrosion and expansion
Visual upper system design and development (Halcon WinForm) -2 Global variable design
Global and Chinese market of Bus HVAC systems 2022-2028: Research Report on technology, participants, trends, market size and share
【注意力机制】【首篇ViT】DETR,End-to-End Object Detection with Transformers网络的主要组成是CNN和Transformer
视觉上位系统设计开发(halcon-winform)-5.相机
The method of parameter estimation of user-defined function in MATLAB
Construction of operation and maintenance system
High quality workplace human beings must use software to recommend, and you certainly don't know the last one
GCC cannot find the library file after specifying the link library path
qt使用QZxing生成二维码
秒杀系统2-Redis解决分布式Session问题
Jvm-09 byte code introduction
win32创建窗口及按钮(轻量级)
Visual host system design and development (Halcon WinForm)
QT common sentence notes