当前位置:网站首页>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 .
边栏推荐
- Redis single thread problem forced sorting layman literacy
- 百度智能云助力石嘴山市升级“互联网+养老服务”智慧康养新模式
- Didi off the shelf! Data security is national security
- Besides lying flat, what else can a 27 year old do in life?
- Qt常用语句备忘
- 什么是embedding(把物体编码为一个低维稠密向量),pytorch中nn.Embedding原理及使用
- SQL server安装位置改不了
- The method of parameter estimation of user-defined function in MATLAB
- Digital image processing -- popular understanding of corrosion and expansion
- redis单线程问题强制梳理门外汉扫盲
猜你喜欢
Functional modules and application scenarios covered by the productization of user portraits
Popular understanding of gradient descent
Introduction to redis master-slave, sentinel and cluster mode
Jvm-05-object, direct memory, string constant pool
Jvm-03-runtime data area PC, stack, local method stack
Tensorflow realizes verification code recognition (III)
What are the composite types of Blackhorse Clickhouse, an OLAP database recognized in the industry
Redis主从、哨兵、集群模式介绍
Kubernetes vous emmène du début à la fin
秒杀系统2-Redis解决分布式Session问题
随机推荐
Neon global and Chinese markets 2022-2028: Research Report on technology, participants, trends, market size and share
SQL server installation location cannot be changed
XWiki Installation Tips
[pytorch learning notes] transforms
视觉上位系统设计开发(halcon-winform)-6.节点与宫格
Redis主从、哨兵、集群模式介绍
Influxdb2 sources add data sources
开启 Chrome 和 Edge 浏览器多线程下载
Popular understanding of ovo and ovr
【pytorch学习笔记】Datasets and Dataloaders
Visual upper system design and development (Halcon WinForm) -4 Communication management
Puppet automatic operation and maintenance troubleshooting cases
【Transform】【NLP】首次提出Transformer,Google Brain团队2017年论文《Attention is all you need》
XWiki安装使用技巧
socket.io搭建分布式Web推送服务器
运维体系的构建
Matlab r2011b neural network toolbox precautions
win32创建窗口及按钮(轻量级)
Using TCL (tool command language) to manage Tornado (for VxWorks) can start the project
App global exception capture