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

边栏推荐
- [combinatorics] permutation and combination (set permutation, step-by-step processing example)
- Didi off the shelf! Data security is national security
- 求字符串函数和长度不受限制的字符串函数的详解
- Dataframe returns the whole row according to the value
- Global and Chinese markets for indoor HDTV antennas 2022-2028: Research Report on technology, participants, trends, market size and share
- Final review points of human-computer interaction
- 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
- [probably the most complete in Chinese] pushgateway entry notes
- 秒杀系统2-Redis解决分布式Session问题
- [Yu Yue education] scientific computing and MATLAB language reference materials of Central South University
猜你喜欢

解决pushgateway数据多次推送会覆盖的问题

【可能是全中文网最全】pushgateway入门笔记
![MySQL reports an error: [error] mysqld: file '/ mysql-bin. 010228‘ not found (Errcode: 2 “No such file or directory“)](/img/cd/2e4f5884d034ff704809f476bda288.png)
MySQL reports an error: [error] mysqld: file '/ mysql-bin. 010228‘ not found (Errcode: 2 “No such file or directory“)

Jvm-06-execution engine

Redis cache penetration, cache breakdown, cache avalanche solution

Kubernetes will show you from beginning to end

Jvm-04-runtime data area heap, method area

Incluxdb2 buckets create database

mysql innodb 存储引擎的特性—行锁剖析

Visual upper system design and development (Halcon WinForm) -4 Communication management
随机推荐
【可能是全中文网最全】pushgateway入门笔记
Kubernetes vous emmène du début à la fin
Using notepad++ to build an arbitrary language development environment
秒杀系统2-Redis解决分布式Session问题
Kubernetes帶你從頭到尾捋一遍
Markdown file titles are all reduced by one level
整形和浮点型是如何在内存中的存储
Chapter 04_ Logical architecture
Jvm-05-object, direct memory, string constant pool
[transform] [NLP] first proposed transformer. The 2017 paper "attention is all you need" by Google brain team
北京共有产权房出租新规实施的租赁案例
"Seven weapons" in the "treasure chest" of machine learning: Zhou Zhihua leads the publication of the new book "machine learning theory guide"
Halcon与Winform学习第一节
求字符串函数和长度不受限制的字符串函数的详解
Search in the two-dimensional array of leetcode sword offer (10)
秒杀系统3-商品列表和商品详情
Visual host system design and development (Halcon WinForm)
视觉上位系统设计开发(halcon-winform)-5.相机
自定义注解
Functional modules and application scenarios covered by the productization of user portraits