当前位置:网站首页>[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 !)
边栏推荐
- Item exception handling in SSM
- Basic knowledge of C language
- Digital filter design matlab
- DSACTF7月re
- 数字滤波器设计——Matlab
- JS batch add event listening onclick this event delegate target currenttarget onmouseenter OnMouseOver
- English translation Arabic - batch English translation Arabic tools free of charge
- Source insight project import and use tutorial
- 8. Compilation errors of C language and Chinese explanation
- Read how to deploy highly available k3s with external database
猜你喜欢

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

Theoretical knowledge of digital image (I) (personal analysis)

4. Const and difine and the problem of initializing arrays with const and define
![[C language] Hanoi Tower problem [recursion]](/img/d8/ff66928c2bc2ad906e38a360a8cf94.png)
[C language] Hanoi Tower problem [recursion]

Longest Palindromic Substring

2. Floating point number, the difference between float and double in C language and how to choose them

JS preventdefault() keyboard input limit onmousewheel stoppropagation stop event propagation

Zfoo adds routes similar to mydog
![Maximum exchange [greedy thought & monotonic stack implementation]](/img/ad/8f0914f23648f37e1d1ce69086fd2e.png)
Maximum exchange [greedy thought & monotonic stack implementation]

“中国网事·感动2022”二季度网络感动人物评选结果揭晓
随机推荐
9. Pointer of C language (1) what is pointer and how to define pointer variables
Solve flask integration_ Error reporting in restplus
[C language] advanced pointer exercise 1
[C language] shutdown game [loop and switch statement]
河北:稳粮扩豆助力粮油生产提质增效
一文读懂如何部署具有外部数据库的高可用 K3s
JVM(二十四) -- 性能监控与调优(五) -- 分析GC日志
[C language] string reverse order implementation (recursion and iteration)
Multi-Modal Knowledge Graph Construction and Application: A Survey
Communication learning static routing across regional networks
[C language] Pointer elementary knowledge points
Two methods to judge the size end
7. Functions of C language, function definitions and the order of function calls, how to declare functions, prime examples, formal parameters and arguments, and how to write a function well
Cdga | how can the industrial Internet industry do a good job in data governance?
[C language] simulation implementation of strlen (recursive and non recursive)
通信网络基础知识01
中国能否在元宇宙的未来发展中取得突破,占领高地?
Tencent cloud deployment lamp_ Experience of building a station
Array method added in ES6
数字图像理论知识(一)(个人浅析)