当前位置:网站首页>Advanced C language pointer (Part 2)
Advanced C language pointer (Part 2)
2022-07-01 08:37:00 【Stir fried rice with lotus root】
Blogger : Stir fried lotus root bibimbap
Blog :(10 Bar message ) The blog of stir fried lotus root bibimbap _CSDN Blog -C Language bloggers
special column :(10 Bar message ) C Language _ The blog of stir fried lotus root bibimbap -CSDN Blog
Column introduction : Contains from C Explain the knowledge points from the beginning to the advanced level of the language , use C Language to write a variety of small programs , Generally around C Basic column ;
Key points of this blog :
1. A function pointer
2. Function pointer array
3. A pointer to an array of function pointers
4. Callback function
1. A function pointer
Function pointer Introduction
First, let's look at a piece of code :
#include <stdio.h>
void test()
{
printf("hehe\n");
}
int main()
{
printf("%p\n", test);
printf("%p\n", &test);
return 0;
}
Output results (%p It's used to print addresses ):

That is to say, whether it is direct printing or & Print test function , It's all the same address , If you have an address, you can use a pointer to point to this function , We call it a function pointer ;
Type definition of function pointer :
Previously, we also learned about various kinds of pointers , for example int *pa,int (*pb)[5] wait ;
Except for the pointer variable name, the rest of their types are their types ,pa The type of int*,pb The type of int(*)[5], Function pointers are no exception :
int add(int a, int b)
{
return a + b;
}
int main()
{
int a = 0;
int b = 0;
int ret=add(a, b);
return 0;
}add A function pointer :int (*ph)(int,int)= add(& not essential );
1.(*ph) Just explain ph It's a pointer
2.(int,int) Note that this pointer points to a function , This function has two arguments , Types are int
3. int It indicates that the return value of this function is int type
int add(int a, int b)
{
return a + b;
}
int main()
{
int a = 5;
int b = 3;
int (*ph)(int, int) = add;
int ret = ph(a, b);//* You may or may not write , But if you want to write, you must add ()
printf("%d", ret); // adopt ph We can also call add function , It's like giving add Function takes a nickname
return 0;
}We have understood the basic definition of function pointer above. Next, let's take a look at two paragraphs from 《c Traps and defects 》 The code of this book :
// Code 1 ( * ( void ( * ) ( ) ) 0 ) ( );
// Code 2 void ( * signal (int , void ( * ) ( int ) ) ) ( int );
Code 1 analysis :
void (*)() We know it is a function pointer type ,(void (*)())0 It's a 0 Force type to void(*)() Such a pointer type , And then add ( * ( void ( * ) ( ) ) 0 ) ( ) Will be 0 Dereference and call , This code is essentially a function call , It's called 0 As a function at the address ;
Code 2 analysis :
First signal And the one in front * Not together () get up , that signal It must be with the back () combination , that sighal It must be a function name ,signal(int,void(*)(int)) On behalf of signal This function has two arguments , One is int type , One is void(*)(int) Function pointer type , So the rest void(*)(int) What is it? ?
yes signal The return type of the function , Its return type is also a function pointer type , After analysis, this code is essentially a signal Declaration of functions ;
Little knowledge : The above types are too complex , Can we use typedef To redefine the type ? The answer is yes !
typedef void ( * pfun_t ) ( int );// Be careful typedef The function pointer type needs to be defined in (*) It is defined
pfun_t signal ( int , pfun_t );
The purpose of the function pointer :
Beginners will have a doubt : Why bother to build a function pointer ? If I want to call a function, just use the function name ? Just like up here add I can use it directly , Why use function pointers ph Well ?
According to the above code, you really don't need a function pointer , But the code above is too simple , For beginners, I seldom touch some advanced code , So I don't agree with function pointers , I can definitely say that function pointers can be counted as C The advanced grammar in the language , And it is often used in complex code !
Take a simple chestnut , We need to write a program to realize calculator ( Integer addition, subtraction, multiplication and division ):
void menu()
{
printf("*****************************\n");
printf("**** 1. add 2. sub *****\n");
printf("**** 3. mul 4. div *****\n");
printf("**** 0. exit *****\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;
int ret = 0;
do
{
menu();
printf(" Please select :>");
scanf("%d", &input);
switch (input)
{
case 1:
printf(" Please enter 2 Operands :>");
scanf("%d %d", &x, &y);
ret = Add(x, y);
printf("%d\n", ret);
break;
case 2:
printf(" Please enter 2 Operands :>");
scanf("%d %d", &x, &y);
ret = Sub(x, y);
printf("%d\n", ret);
break;
case 3:
printf(" Please enter 2 Operands :>");
scanf("%d %d", &x, &y);
ret = Mul(x, y);
printf("%d\n", ret);
break;
case 4:
printf(" Please enter 2 Operands :>");
scanf("%d %d", &x, &y);
ret = Div(x, y);
printf("%d\n", ret);
break;
case 0:
printf(" Exit calculator \n");
break;
default:
printf(" Wrong choice \n");
break;
}
} while (input);
return 0;
}
I believe you are familiar with writing such code , But we found that such code is not too redundant ,switch Under the sentence case Statement item code repetition is too high , Can we take it out and package it into a function :
The subject sentence :
void menu()
{
printf("*****************************\n");
printf("**** 1. add 2. sub *****\n");
printf("**** 3. mul 4. div *****\n");
printf("**** 0. exit *****\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;
do
{
menu();
printf(" Please select :>");
scanf("%d", &input);
switch (input)
{
case 1:
calc(Add);
break;
case 2:
calc(Sub);
break;
case 3:
calc(Mul);
break;
case 4:
calc(Div);
break;
case 0:
printf(" Exit calculator \n");
break;
default:
printf(" Wrong choice \n");
break;
}
} while (input);
return 0;
}We achieve one calc function , Transfer the corresponding calculation function for any calculation ;
calc function :
void calc(int (*pf)(int , int))
{
int x = 0;
int y = 0;
int ret = 0;
printf(" Please enter 2 Operands :>");
scanf("%d %d", &x, &y);
ret = pf(x, y);
printf("%d\n", ret);
}Does it simplify the whole code by using function pointers , And this is not the simplest way , Using arrays we can make the code simpler ( Function pointer array )!
2. Function pointer array
The function pointer array is an array , All of its element types are function pointer types ;
According to the calculator code we wrote above , Since a function pointer is a type , And the types of the above addition, subtraction, multiplication and division functions are the same , Then we can put them in an array , Which function you need to call directly through subscript ;
void menu()
{
printf("*****************************\n");
printf("**** 1. add 2. sub *****\n");
printf("**** 3. mul 4. div *****\n");
printf("**** 0. exit *****\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;
int ret = 0;
// An array of function pointers
// Transfer table
int (*pfArr[])(int, int) = {0, Add, Sub, Mul, Div};//[] representative pfArr It points to an array
do
{
menu();
printf(" Please select :>");
scanf("%d", &input);
if (input == 0)
{
printf(" Exit calculator \n");
}
else if (input >= 1 && input <= 4)
{
printf(" Please enter 2 Operands :>");
scanf("%d %d", &x, &y);
ret = pfArr[input](x, y);
printf("%d\n", ret);
}
else
{
printf(" Wrong choice \n");
}
} while (input);
return 0;
}
It is also convenient for us to add other functions next time , You can add it directly to the element initialization of the array , The following code just needs to be fine tuned ;
3. A pointer to an array of function pointers
A pointer to an array of function pointers It's a The pointer , The pointer points to a Array , The elements of the array are A function pointer ;
Define methods :
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; }Here is just a rough introduction , After all, it's possible to keep dolls here , And such code is relatively rare , It is enough to know such code ;
4. Callback function
A callback function is a function called through a function pointer . If you put a pointer to a function ( Address ) Pass as a parameter to another function , When this pointer is used to call the function it points to , Let's just say this is a 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 enter the event or condition Row response .
qsort function :
stay C The library function of language has a qosrt function , This function can sort various types of data , The sorting method we usually write is type dead ,int Types can only be sorted int type , Floating point types can only sort floating point types ;

qsort Functions have 4 Parameters , The first parameter Is the starting address of the data to be sorted , The second parameter Is the number of elements to be sorted , The third parameter Is the size of each element ( byte ), Fourth parameter Is a function pointer , This function requires the user to write a comparison function ;
#include <stdio.h>
//qosrt The user of the function has to implement a comparison function
int int_cmp(const void * p1, const void * p2)
{
return (*( int *)p1 - *(int *) p2);
}
int main()
{
int arr[] = { 1, 3, 5, 7, 9, 2, 4, 6, 8, 0 };
int i = 0;
qsort(arr, sizeof(arr) / sizeof(arr[0]), sizeof (int), int_cmp);
for (i = 0; i< sizeof(arr) / sizeof(arr[0]); i++)
{
printf( "%d ", arr[i]);
}
printf("\n");
return 0;
}
Use callback function simulation to realize a qsort function :
#include <stdio.h>
int int_cmp(const void * p1, const void * p2)
{
return (*( int *)p1 - *(int *) p2);
}
void _swap(void *p1, void * p2, int size)
{
int i = 0;
for (i = 0; i< size; i++)
{
char tmp = *((char *)p1 + i);
*(( char *)p1 + i) = *((char *) p2 + i);
*(( char *)p2 + i) = tmp;
}
}
void bubble(void *base, int count , int size, int(*cmp )(void *, void *))
{
int i = 0;
int j = 0;
for (i = 0; i< count - 1; i++)
{
for (j = 0; j<count-i-1; j++)
{
if (cmp ((char *) base + j*size , (char *)base + (j + 1)*size) > 0)
{
_swap(( char *)base + j*size, (char *)base + (j + 1)*size, size);
}
}
}
}
int main()
{
int arr[] = { 1, 3, 5, 7, 9, 2, 4, 6, 8, 0 };
//char *arr[] = {"aaaa","dddd","cccc","bbbb"};
int i = 0;
bubble(arr, sizeof(arr) / sizeof(arr[0]), sizeof (int), int_cmp);
for (i = 0; i< sizeof(arr) / sizeof(arr[0]); i++)
{
printf( "%d ", arr[i]);
}
printf("\n");
return 0;
}边栏推荐
- Principle and application of single chip microcomputer - off chip development
- Leetcode T29: 两数相除
- Hijacking a user's browser with beef
- 【面试必刷101】链表
- XX attack - reflective XSS attack hijacking user browser
- Audio-AudioRecord create(一)
- Intelligent water and fertilizer integrated control system
- Introduction to 18mnmo4-5 steel plate executive standard and delivery status of 18mnmo4-5 steel plate, European standard steel plate 18mnmo4-5 fixed rolling
- SPL installation and basic use (II)
- What is the material of 16MnDR, the minimum service temperature of 16MnDR, and the chemical composition of 16MnDR
猜你喜欢

01 numpy introduction

Conception et mise en service du processeur - chapitre 4 tâches pratiques

Airsim radar camera fusion to generate color point cloud

Manually dig XSS vulnerabilities

《单片机原理与应用》——并行IO口原理

機動目標跟踪——當前統計模型(CS模型)擴展卡爾曼濾波/無迹卡爾曼濾波 matlab實現

"Analysis of 43 cases of MATLAB neural network": Chapter 30 design of combined classifier based on random forest idea - breast cancer diagnosis

When using charts to display data, the time field in the database is repeated. How to display the value at this time?

网关gateway-88

MD文档中插入数学公式,Typora中插入数学公式
随机推荐
Properties of 15MnNiNbDR low temperature vessel steel, Wugang 15MnNiDR and 15MnNiNbDR steel plates
《微机原理》—总线及其形成
[deep analysis of C language] - data storage in memory
Leetcode t39: combined sum
View drawing process analysis
Yolov5进阶之七目标追踪最新环境搭建
Yolov5 advanced 7 target tracking latest environment setup
《单片机原理与应用》——并行IO口原理
leetcode T31:下一排列
避免按钮重复点击的小工具bimianchongfu.queren()
Count number of rows per group and add result to original data frame
Manually dig XSS vulnerabilities
Centos7 shell脚本一键安装jdk、mongo、kafka、ftp、postgresql、postgis、pgrouting
vscode自定义各个区域的颜色
《微机原理》-绪论
19Mn6 German standard pressure vessel steel plate 19Mn6 Wugang fixed binding 19Mn6 chemical composition
Matlab [function derivation]
15Mo3 German standard steel plate 15Mo3 chemical composition 15Mo3 mechanical property analysis of Wuyang Steel Works
【无标题】
Comprehensive experiment Li
