当前位置:网站首页>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 .
边栏推荐
- Visual upper system design and development (Halcon WinForm) -1 Process node design
- mysql innodb 存储引擎的特性—行锁剖析
- Visual host system design and development (Halcon WinForm)
- 【云原生训练营】模块七 Kubernetes 控制平面组件:调度器与控制器
- 自定义注解
- Visual upper system design and development (Halcon WinForm) -2 Global variable design
- Jvm-09 byte code introduction
- 北京共有产权房出租新规实施的租赁案例
- [pytorch learning notes] transforms
- 如何使用 @NotNull等注解校验 并全局异常处理
猜你喜欢
Concurrency-01-create thread, sleep, yield, wait, join, interrupt, thread state, synchronized, park, reentrantlock
什么是one-hot encoding?Pytorch中,将label变成one hot编码的两种方式
【pytorch学习笔记】Datasets and Dataloaders
Popular understanding of ovo and ovr
Chapter 04_ Logical architecture
Unity hierarchical bounding box AABB tree
北京共有产权房出租新规实施的租赁案例
[cloud native training camp] module VIII kubernetes life cycle management and service discovery
Concurrency-02-visibility, atomicity, orderliness, volatile, CAS, atomic class, unsafe
redis缓存穿透,缓存击穿,缓存雪崩解决方案
随机推荐
Matplotlib drawing label cannot display Chinese problems
socket. IO build distributed web push server
Solve the problem that pushgateway data will be overwritten by multiple push
[transformer] Introduction - the original author of Harvard NLP presented the annotated transformer in the form of line by line implementation in early 2018
Using multipleoutputs to output multiple files in MapReduce
Kubernetes will show you from beginning to end
SQL server installation location cannot be changed
App全局异常捕获
Visual upper system design and development (Halcon WinForm) -4 Communication management
What is one hot encoding? In pytoch, there are two ways to turn label into one hot coding
Tensorflow realizes verification code recognition (III)
基于SVN分支开发模式流程浅析
Besides lying flat, what else can a 27 year old do in life?
Jvm-09 byte code introduction
The method of parameter estimation of user-defined function in MATLAB
需要知道的字符串函数
Concurrency-02-visibility, atomicity, orderliness, volatile, CAS, atomic class, unsafe
Detailed comments on MapReduce instance code on the official website
Visual upper system design and development (Halcon WinForm) -3 Image control
Kubernetes advanced training camp pod Foundation