当前位置:网站首页>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;
}
边栏推荐
- 为什么LTD独立站就是Web3.0网站!
- Vscode customize the color of each area
- Field agricultural irrigation system
- 《微机原理》—总线及其形成
- Thread safety analysis of [concurrent programming JUC] variables
- [untitled]
- What is the material of 16mo3 steel plate? What is the difference between 16mo3 and Q345R?
- 截图小妙招
- Review of week 280 of leetcode
- shardingSphere
猜你喜欢
Audio audiorecord create (I)
基础:2.图像的本质
Hijacking a user's browser with beef
Li Kou 1358 -- number of substrings containing all three characters (double pointer)
Suivi des cibles de manoeuvre - - mise en oeuvre du modèle statistique actuel (modèle CS) filtre Kalman étendu / filtre Kalman sans trace par MATLAB
[detailed explanation of Huawei machine test] judgment string subsequence [2022 Q1 Q2 | 200 points]
The use of word in graduation thesis
Using settoolkit to forge sites to steal user information
Brief introduction to AES
【无标题】
随机推荐
C语言指针的进阶(下)
基础:2.图像的本质
《微机原理》—总线及其形成
Matlab tips (23) matrix analysis -- simulated annealing
NFT监管要点和海外政策
[Yu Yue education] Shandong Vocational College talking about railway reference materials
AES简单介绍
Stack implementation calculator
Maneuvering target tracking -- current statistical model (CS model) extended Kalman filter / unscented Kalman filter matlab implementation
yolov5训练可视化指标的含义
Li Kou 1358 -- number of substrings containing all three characters (double pointer)
【面试必刷101】链表
Luogu p3799 demon dream stick
2022 Chinese cook (technician) simulation test and Chinese cook (technician) practice test video
DID的使用指南,原理
Provincial election + noi Part VII computational geometry
Review of week 280 of leetcode
The era of low threshold programmers is gone forever behind the sharp increase in the number of school recruitment for Internet companies
Pipeline detection of UAV Based on gazebo
Manually dig XSS vulnerabilities