当前位置:网站首页>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 .

边栏推荐
- win32创建窗口及按钮(轻量级)
- Atlas atlas torque gun USB communication tutorial based on mtcom
- Can‘t connect to MySQL server on ‘localhost‘
- Jvm-02-class loading subsystem
- Global and Chinese markets for infrared solutions (for industrial, civil, national defense and security applications) 2022-2028: Research Report on technology, participants, trends, market size and sh
- 【pytorch学习笔记】Datasets and Dataloaders
- 整形和浮点型是如何在内存中的存储
- 基于SVN分支开发模式流程浅析
- Enable multi-threaded download of chrome and edge browsers
- 【Transform】【NLP】首次提出Transformer,Google Brain团队2017年论文《Attention is all you need》
猜你喜欢
![[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

Dataframe returns the whole row according to the value

The state does not change after the assignment of El switch

Halcon与Winform学习第二节

Concurrency-02-visibility, atomicity, orderliness, volatile, CAS, atomic class, unsafe

Jvm-08-garbage collector

High quality workplace human beings must use software to recommend, and you certainly don't know the last one

【Transformer】入门篇-哈佛Harvard NLP的原作者在2018年初以逐行实现的形式呈现了论文The Annotated Transformer

Jvm-05-object, direct memory, string constant pool
![[transform] [NLP] first proposed transformer. The 2017 paper](/img/33/f639ab527d5adedfdc39f8d8117c3e.png)
[transform] [NLP] first proposed transformer. The 2017 paper "attention is all you need" by Google brain team
随机推荐
Leasing cases of the implementation of the new regulations on the rental of jointly owned houses in Beijing
Global and Chinese market of Bus HVAC systems 2022-2028: Research Report on technology, participants, trends, market size and share
Halcon与Winform学习第一节
Matplotlib drawing label cannot display Chinese problems
解决pushgateway数据多次推送会覆盖的问题
视觉上位系统设计开发(halcon-winform)-2.全局变量设计
Using Tengine to solve the session problem of load balancing
Halcon与Winform学习第二节
视觉上位系统设计开发(halcon-winform)
秒杀系统2-Redis解决分布式Session问题
Kubernetes - yaml file interpretation
Redis cache penetration, cache breakdown, cache avalanche solution
Using multipleoutputs to output multiple files in MapReduce
[Yu Yue education] scientific computing and MATLAB language reference materials of Central South University
Finally, someone explained the financial risk management clearly
【注意力机制】【首篇ViT】DETR,End-to-End Object Detection with Transformers网络的主要组成是CNN和Transformer
socket.io搭建分布式Web推送服务器
Construction of operation and maintenance system
Win10 enterprise 2016 long term service activation tutorial
高并发下之redis锁优化实战