当前位置:网站首页>Pointer from beginner to advanced (2)
Pointer from beginner to advanced (2)
2022-06-29 06:15:00 【Xiao Mofan】
Catalog
3.1 Definition of array pointer
3.2& Array name and array name
Four 、 Parameter passing of pointer
5、 ... and 、 A function pointer
5.2 Feel the happiness of function pointer
5.2.1 analysis ( * ( void ( * ) ( ) ) 0 ) ( ); Code
5.2.2 analysis void ( * signal ( int , void ( * ) ( int ) ) ) ( int ); Code
6、 ... and 、 Function pointer array
One 、 Character pointer
When defining character pointers , There are two ways of writing :
// The first one is char ch[] = "hello";// Define a constant string char* ptr = &ch; // Take out ch The address of , Save to character pointer ptr in // The second kind char* str = "hello";// Direct the character pointer to the constant stringMaybe when touching the character pointer , Have had such an idea —— Since the string is stored in a pointer variable , Then the dereference operation should be output as is , But that's not the case , Its essence is to store the address of the first character of the string in the pointer variable , The pointer can find this contiguous space and access it through this address ;
Answer the question with the following code :
#include <stdio.h>
int main()
{
char ch[] = "hello";
char* ptr = &ch;
char* str = "hello";
printf("%c\n", *ptr);
printf("%c\n", *(ptr+1));
printf("%c\n", *str);
printf("%c\n", *(str + 1));
return 0;
}
From the results of operation , The result of dereference is h, explain ptr Pointers and str The pointer stores h The address of ,*(ptr+1) The printed result is e, The description string is also accessed by subscript ( Continuous space );
Two 、 Pointer array
Concept : I have an array , The elements stored in the array are pointers ( Address ) ;

#include <stdio.h>
int main()
{
int a = 10;
int b = 20;
int c = 30;
int* arr[3] = { &a,&b,&c };// This is how the pointer array is defined
printf("%d\n", *arr[0]);// or **arr
//**arr---arr Is the array name, that is, the address of the first element , After dereferencing, we get &a , And then you can get 10
return 0;
}3、 ... and 、 Array pointer
3.1 Definition of array pointer
Array pointer is a pointer or an array ?( The answer is : The pointer )
Compare the following two codes :
int* p1[5];// Pointer array int (*p2)[5];// Array pointer ( Row pointer )( ) The priority of [ ] higher ; [ ] The priority of * higher ;
1. p1 With the first [ ] Combined table name p It's an array , This array has 5 Elements , The type of each element is int*;
2. p2 With the first * combination , indicate p2 Is a pointer , Points to an array , Each element group has 5 Elements , The type of each element is int;
3.2& Array name and array name
The array name indicates the address of the first element of the array , that & What does the array name mean ?
#include <stdio.h>
int main()
{
int arr[10] = { 0 };
printf("arr = %p\n", arr);
printf("&arr= %p\n", &arr);
printf("arr+1 = %p\n", arr+1);
printf("&arr+1= %p\n", &arr+1);
return 0;
}
3.3 The use of array pointers
Often used for two-dimensional arrays
#include <stdio.h>
int main()
{
int arr[2][5] = { 0,1,2,3,4,5,6,7,8,9 };
int(*parr)[5] = &arr;
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < 5; j++)
{
printf("%d ", parr[i][j]);
//printf("%d ", (*(parr+i))[j]);
//printf("%d ", *(parr[i] + j));
//printf("%d ", *(*(parr + i)+j));
}
printf("\n");
}
return 0;
}parr[ i ] [ j ] = ( * ( parr + i ) ) [ j ] ) = * ( parr [ i ] + j ) = * ( * ( parr + i ) + j );

Four 、 Parameter passing of pointer
The ginseng : The essential meaning is that the transmitter and the receiver are of the same type or the receiver belongs to any type of acceptance ( Such as :void)
#include <stdio.h>
void print_arr1(int arr[3][5], int row, int col)
{// This is a common two-dimensional array parameter transfer , When transferring parameters, note that rows can be omitted, but columns cannot
int i = 0;
for (i = 0; i < row; i++)
{
for (int j = 0; j < col; j++)
{
printf("%d ", arr[i][j]);
}
printf("\n");
}
}
void print_arr2(int(*arr)[5], int row, int col)
{// Here, the address of the first row of the two-dimensional array is passed to an array pointer
int i = 0;
for (i = 0; i < row; i++)
{
for (int j = 0; j < col; j++)
{
printf("%d ", arr[i][j]);
}
printf("\n");
}
}
int main()
{
int arr[3][5] = { 1,2,3,4,5,6,7,8,9,10 };
print_arr1(arr, 3, 5);
// Array name arr, Represents the address of the first element
// But the first element of a two-dimensional array is the first row of a two-dimensional array
// So the message here is arr, It's actually equivalent to the address on the first line , Is the address of a one-dimensional array
// You can use an array pointer to receive
print_arr2(arr, 3, 5);
return 0;
}}
5、 ... and 、 A function pointer
Essential meaning : Is to store the address of the function in a pointer variable ;
5.1 Code Introduction
#include <stdio.h>
int Add(int a, int b)
{
return a + b;
}
int main()
{
int a = 10;
int b = 20;
int (*pa)(int, int) = Add;
int ret = pa(a, b);
printf("%d\n", ret);
return 0;
}int (*pa)(int, int) = Add;
Add Is the function name , It's the address of the function ,Add The type is int (int a, int b); Save it in a pointer variable , The type of this pointer variable should also be int ( * ) (int a, int b), Or you could write it as int( * ) (int , int )
It must not be written as int *pa(int, int) = Add; In this code pa It is expressed as a function , The type is int*, So the parentheses are Very important Of
int ret = pa(a, b);pa Deposit is Add Address of function , Here we use pa To call Add function , And give it a reference ;
5.2 Feel the happiness of function pointer
5.2.1 analysis ( * ( void ( * ) ( ) ) 0 ) ( ); Code

5.2.2 analysis void ( * signal ( int , void ( * ) ( int ) ) ) ( int ); Code

6、 ... and 、 Function pointer array
meaning : It's essentially an array , The elements in the array are function pointers ; To put it simply , There is an array containing the addresses of many functions
int (*p[5])(int,int);p[ 5 ] Indicates an array , Its type is int ( * )( int , int );
Without touching the function pointer array , If you want to write a code to add, subtract, multiply and divide Calculator , We can take advantage of switch Statement to select function functions , The code is as follows ;
#include <stdio.h>
int add(int a, int b)
{
return a + b;
}
int sub(int a, int b)
{
return a - b;
}
int mul(int a, int b)
{
return a * b;
}
int div(int a, int b)
{
return a / b;
}
int main()
{
int x, y;
int input = 1;
int ret = 0;
do
{
printf("*************************\n");
printf("****1:add 2:sub****\n");
printf("****3:mul 4:div****\n");
printf("*************************\n");
printf(" Please select :");
scanf("%d", &input);
switch (input)
{
case 1:
printf(" Enter the operands :");
scanf("%d %d", &x, &y);
ret = add(x, y);
printf("ret = %d\n", ret);
break;
case 2:
printf(" Enter the operands :");
scanf("%d %d", &x, &y);
ret = sub(x, y);
printf("ret = %d\n", ret);
break;
case 3:
printf(" Enter the operands :");
scanf("%d %d", &x, &y);
ret = mul(x, y);
printf("ret = %d\n", ret);
break;
case 4:
printf(" Enter the operands :");
scanf("%d %d", &x, &y);
ret = div(x, y);
printf("ret = %d\n", ret);
break;
case 0:
printf(" Exit procedure \n");
break;
default:
printf(" Wrong choice \n");
break;
}
} while (input);
return 0;
}Implementation using function pointer array :
#include <stdio.h>
int add(int a, int b)
{
return a + b;
}
int sub(int a, int b)
{
return a - b;
}
int mul(int a, int b)
{
return a * b;
}
int div(int a, int b)
{
return a / b;
}
int main()
{
int x, y;
int input = 1;
int ret = 0;
int(*p[5])(int x, int y) = { 0, add, sub, mul, div };
while (input)
{
printf("*************************\n");
printf("****1.add 2.sub****\n");
printf("****3.mul 4.div****\n");
printf("*************************\n");
printf(" Please select :");
scanf("%d", &input);
if ((input <= 4 && input >= 1))
{
printf(" Enter the operands :");
scanf("%d %d", &x, &y);
ret = (*p[input])(x, y);// Input input Respectively corresponding to the subscript of the corresponding function in the function pointer
}
else
printf(" Incorrect input \n");
printf("ret = %d\n", ret);
}
return 0;
}7、 ... and 、 A pointer to an array of function pointers
How to define :
// A function pointer p
int (*p)(int x,int y);
// An array of function pointers p1
int (*p1[5])(int x,int y)=&p;
// Pointer to function array p1 The pointer to p2
int (*(*p2)[5])(int x,int y) = &p1;

#include <stdio.h>
int add(int a, int b)
{
return a + b;
}
int main()
{
// A function pointer p
int (*p)(int x, int y) = add;
// An array of function pointers p1
int (*p1[4])(int x, int y) = { p };// Here you can also subtract 、 Multiplication 、 The address of the division function is saved in
// Pointer to function array p1 The pointer to p2
int (*(*p2)[4])(int x, int y) = &p1;
// Use the pointer to the function pointer array to add two numbers
int ret = (*(*p2[0]))(10, 5);
printf("ret=%d\n", ret);
return 0;
}8、 ... and 、 summary
All contents of the above pointer advanced , The understanding of the pointer in this paper is mainly based on the author's own statement , There is no professional explanation , I hope that reading these two pointers can help you .
边栏推荐
- Slot
- Loosely matched jest A value in tohavebeencalledwith - loose match one value in jest toHaveBeenCalledWith
- How to insert pseudo code into word documents simply and quickly?
- 2-nitro-5,10,15,20-tetra (3,5-dimethoxyphenyl) porphyrin (no2tdmpp) H2) /5,10,15,20-tetra (4-methylphenyl) porphyrin (TMPP) H2) Qiyue porphyrin products
- Two houses with different colors and the farthest distance
- Analysis report on the investment market of the development planning prospect of the recommended rare earth industry research industry in 2022 (the attachment is a link to the online disk, and the rep
- Week 10 - task 0- execution process instance resolution of constructors and destructors
- Pytest (7) -yield and termination function
- Purple red solid meso tetra (o-alkoxyphenyl) porphyrin cobalt (meso-t (2-rop) PCO) / tetra (n, n-diphenyl-p-amino) phenyl porphyrin (tdpatph2)
- Rich material libraries make modeling easy and efficient for developers
猜你喜欢

HTTP Caching Protocol practice

Devops development, operation and maintenance Basics: using Jenkins to automatically build projects and notify by email

Why Houdini made the pyside2 plug-in crash

Browser local storage

Principle of screen printing adjustment of EDA (cadence and AD) software

Maximum ascending subarray sum of leetcode simple problem

VLAN experiment

Servlet version conflict causes page 404

National Defense University project summary

Sum of digits under k-ary representation of leetcode simple problem
随机推荐
Research Report on the new energy industry of recommended power equipment in 2022 industry development prospect market investment analysis (the attachment is a link to the network disk, and the report
Honeypot based on MySQL load data local INFILE
Design of leetcode simple problem goal parser
Call the computer calculator and use it to convert several base numbers
51 single chip microcomputer learning notes 7 -- Ultrasonic Ranging
AIRNET notes 1
Agile invincible event
Week 10 - task 1- fill in the blank: line class inherits point class
2022 recommended quantum industry research industry development planning prospect investment market analysis report (the attachment is a link to the online disk, and the report is continuously updated
2022 recommended RCEP regional comprehensive economic partnership agreement market quotation Investment Analysis Industry Research Report (the attachment is a link to the online disk, and the report i
Multiline regular expression search in Visual Studio code - multiline regular expression search in Visual Studio code
Top ten Devops best practices worthy of attention in 2022
Can I cast int to a variable of type byte? What happens if the value is larger than the range of byte type?
2022 recommended precious metal industry research report industry development prospect market analysis white paper (the attachment is a link to the online disk, and the report is continuously updated)
Week 12 - task 2- shoulder to shoulder cadres
Can redis implement hot standby?
Design and practice of kubernetes cluster and application monitoring scheme
2022 recommended prefabricated construction industry research report industry development prospect market analysis white paper (the attachment is a link to the network disk, and the report is continuo
Activiti Designer
Installing modules in pycharm

From the results of operation , The result of dereference is 

