当前位置:网站首页>[C language] comprehensively analyze the pointer and sort out the pointer knowledge points
[C language] comprehensively analyze the pointer and sort out the pointer knowledge points
2022-07-28 20:15:00 【White Hibiscus KK】
Catalog
3.1 The origin of wild pointer :
3.2 How to avoid wild pointer ?
4. The operation of the pointer
Preface :
Yes C language , Pointer is a difficult point , If you use C Language to write data structures , It is necessary to master the usage of pointers , If the pointer doesn't learn well , It's hard to learn data structure . So I hope you must master the pointer !!!
1. The concept of pointer
1. The pointer is a Variable , be used for Storage address , The address uniquely represents a piece of memory space .
ps:( Memory number = Address = The pointer )
2. What is the size of the pointer fixed 4/8 Bytes (32 Bit platform /64 Bit platform )
2. The type of pointer
Pointers are typed , The type of pointer determines the pointer +- Integer step size , Pointer dereference permission .
Now let me explain the meaning of the red part above , for instance , Take a look at the following code and running results :
#include<stdio.h>
int main()
{
int a = 4;
int* p1 = &a;
char* p2 = &a;
printf("%p\n", p1);
printf("%p\n", p2);
printf("%p\n", p1+1);
printf("%p\n", p2+1);
return 0;
}
At first p1 and p2 The address is the same , But back let p1 and p2 separately +1, The later result is different ,p1 Plus 1 yes int Type of 1, and p2+1 Plus char Type of 1.
As we mentioned above, the size of the pointer is fixed 4/8 Bytes , The assumption is 32 Bit platform , Then a pointer will occupy 4 Bytes . If I define an integer pointer and a character pointer , So this Integer pointer When dereferencing, you can access 4 Bytes , and Character pointer You can only visit 1 Bytes .
3. Wild pointer
The concept of wild pointer is : The position of the pointer is unknown
3.1 The origin of wild pointer :
It's a wild pointer origin There are two :1. Pointer not initialized 2. Pointer out of bounds access
Explain to you :
Pointer not initialized
This should be well understood , That is, when we create a pointer variable, we don't let it point to any object
for example : int* p; such p It's a local variable ,p It's just one. Random value
Pointer out of bounds access
Take a look at the following code :
#include<stdio.h>
int main()
{
int arr[5] = { 1,2,3,4,5 };
int* p = arr;
int i = 0;
for (i = 0; i < 6; i++)
{
printf("%d ", *p);
p++;
}
return 0;
}First, explain the principle of this code ,int* p = arr; here arr It's an array name , The array name is the address of the first element
So now p Is the address of the first element Yes p Dereference is *p ,*p The value is 1
p++; This line of code is to make p The address of ++; What is the size of the pointer fixed 4/8 Bytes , int Type data in C Language is also 4/8 Bytes , All the pointers we get are data The address of the first byte , And the array in memory is continuity Of ,p++ Just move one data back .
But now arr The array has only 5 Elements , But the cycle 6 This will inevitably lead to the out of bounds of the array , Let's take a look at the running results

front 5 The number is arr The number in the array , The first 6 A value is a random value . Because when you cycle to the 6 When the time ,p There is no object to point to , here p It's a wild pointer .
3.2 How to avoid wild pointer ?
1. Good at using NULL, Initialize the pointer in time
If you are defining pointer variables , I have thought of the object pointed to by the pointer variable , Then initialize directly .
If you are defining , It's not clear what the pointer points to , It's not clear whether to use a pointer later , Then assign the pointer variable NULL
NULL It means empty , If int *p=NULL; So at this time p Is a null pointer , You can re assign values later , It does not affect the later use . If a pointer is a null pointer , Don't use it before you initialize it .
2. Avoid pointer out of bounds
3. Avoid returning the address of a local variable
4. The operation of the pointer
Look at the following code :
#include<stdio.h>
int main()
{
// Pointer address plus or minus integer
int arr[5] = { 1,2,3,4,5 };
int* p1 = arr;
int i = 0;
for (i = 0; i < 5; i++)
{
printf("%d ", *p1);
p1++;
}
printf("\n");
// Dereferenced pointer plus or minus integers
int b = 10;
int* p2 = &b;
(*p2)++;
printf("%d", *p2);
return 0;
}p1++ Is an integer that adds or subtracts an address , We've already talked about that , Now I won't introduce more
and (*p2)++, I defined a b Variable , And then assigned to 10, And then put b The address of p2,*p2 By dereferencing, we get 10,(*p)++ amount to 10++ , What you get is 11.
So let's see what happens :

ps: Pointers can compare sizes
The pointer can also be subtracted
for instance :
#include<stdio.h>
int main()
{
int arr[5] = { 1,2,3,4,5 };
printf("%d", &arr[4] - &arr[0]);
return 0;
}There is no pointer variable subtraction , It's the same thing . After all, the pointer is the address .
When two pointers point to the same space , The absolute value of pointer minus pointer is the number of data between these two pointers .
Note that this is not Number * The size of the data type C According to the language

5. Pointers and arrays
1. Arrays can be accessed through pointers , You can refer to the code I wrote above .
2. Usually The array name is the address of the first element
But there are exceptions to everything :
1.sizeof( Array name ) What you get is the size of the entire array
2.&+ Array name Here is the address of the entire array .
3. When transferring function parameters , If the parameter is an array , Formal parameters can be designed as pointers , Of course, if the formal parameter is an array , You can also pass a pointer as an argument .
6. The secondary pointer
The secondary pointer is used to store the primary pointer ( Pointer to the variable ) The address of .
#include<stdio.h>
int main()
{
int a = 5;
int* pa = &a;
int** ppa = &pa;
return 0;
}here pa Is the first level pointer ,ppa It's a secondary pointer ,ppa It's a pa Take out the address of and put it in ppa Inside
**ppa Namely *pa find pa, In the face of pa Dereference to find a
7. Pointer array
The definition of pointer array :int* Array name [ size ]
Pointer array usage :
#include<stdio.h>
int main()
{
int arr1[3] = { 1,2,3 };
int arr2[3] = { 4,5,6, };
int* arr3[2] = {arr1,arr2};
int i = 0;
int j = 0;
for (i = 0; i < 2; i++)
{
for (j = 0; j < 3; j++)
{
printf("%d ", *(arr3[i] + j));
}
printf("\n");
}
}The pointer array can be simulated as a two-dimensional array ,arr[i] What's in it is arr1 and arr2 The address of .+j Is to get the address of each array element , Coming * Dereference to get the value inside . Export that place also Can be replaced by printf("%d ", arr3[i][j]); The effect is the same .

summary :
Pointers are really important ! Pointers are really important ! Pointers are really important !( Important things are to be repeated for 3 times ) Be sure to master
I hope this article can help you ( Level co., LTD. , If there are questions , Welcome the boss to correct ! thank !)
边栏推荐
- Rand function generates pseudo-random numbers
- Reverse string
- 4. Const and difine and the problem of initializing arrays with const and define
- JS preventdefault() keyboard input limit onmousewheel stoppropagation stop event propagation
- 9. Pointer of C language (1) what is pointer and how to define pointer variables
- 河北邯郸:拓展基层就业空间 助力高校毕业生就业
- WFST decoding process
- 2022年下半年系统集成项目管理工程师认证8月20日开班
- C language functions and pointers
- Labelme (I)
猜你喜欢

XOR operation and its usage

9. Pointer of C language (5) how many bytes does the pointer variable occupy

DSACTF7月re

数字滤波器设计——Matlab

Can China make a breakthrough in the future development of the meta universe and occupy the highland?

Getting started with enterprise distributed crawler framework

The results of the second quarter online moving people selection of "China Internet · moving 2022" were announced

adb remount of the / superblock failed: Permission denied

5. Difference between break and continue (easy to understand version)

Rand function generates pseudo-random numbers
随机推荐
[C language] Hanoi Tower problem [recursion]
Idea properties file display \u solution of not displaying Chinese
数字滤波器设计——Matlab
local/chain/run_ tdnn.sh:
Can China make a breakthrough in the future development of the meta universe and occupy the highland?
C+ + core programming
[C language] shutdown game [loop and switch statement]
9. Pointer of C language (1) what is pointer and how to define pointer variables
[C language] summary of methods for solving the greatest common divisor
The results of the second quarter online moving people selection of "China Internet · moving 2022" were announced
HSETNX KEY_NAME FIELD VALUE 用法
C language functions and pointers
Find the memory occupied by the structure
Data system of saltstack
Two methods to judge the size end
[C language] Fibonacci sequence [recursion and iteration]
Reverse string
Labelme(一)
C language - data type
JVM(二十四) -- 性能监控与调优(五) -- 分析GC日志