当前位置:网站首页>[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 !)
边栏推荐
- Richpedia: A Large-Scale, Comprehensive Multi-Modal Knowledge Graph
- [C language] function
- Hebei: stabilizing grain and expanding beans to help grain and oil production improve quality and efficiency
- Machine learning -- model evaluation, selection and verification
- BeanFactory not initialized or already closed - call ‘refresh‘ before accessing beans via the Applic
- [C language] Pointer elementary knowledge points
- 1、 Relationship among CPU, memory and hard disk
- robobrowser的简单使用
- C language - data storage
- Implementation of memcpy in C language
猜你喜欢

C+ + core programming

Cdga | how can the industrial Internet industry do a good job in data governance?

Read how to deploy highly available k3s with external database

English translation Portuguese - batch English conversion Portuguese - free translation and conversion of various languages

9. Pointer of C language (1) what is pointer and how to define pointer variables
![[C language] step jumping problem [recursion]](/img/0c/32870484e89b494e41068f7c38b08e.png)
[C language] step jumping problem [recursion]

Stories of Party members | Li qingai uses cartoons to drive farmers to increase income and become rich
![[C language] initial C language reflection and summary](/img/21/826d144867f7a73ec2cd8896a5250a.png)
[C language] initial C language reflection and summary

熊市下PLATO如何通过Elephant Swap,获得溢价收益?

Source insight project import and use tutorial
随机推荐
河北邯郸:拓展基层就业空间 助力高校毕业生就业
Token verification program index.php when configuring wechat official account server
Basic usage of docker
plt. What does it mean when linestyle, marker, color equals none in plot()
[C language] random number generation and `include < time. H > 'learning
[C language] function
KubeEdge发布云原生边缘计算威胁模型及安全防护技术白皮书
Kubeedge releases white paper on cloud native edge computing threat model and security protection technology
“中国网事·感动2022”二季度网络感动人物评选结果揭晓
Can China make a breakthrough in the future development of the meta universe and occupy the highland?
[C language] Pointer elementary knowledge points
WPF--实现WebSocket服务端
Communication learning static routing across regional networks
Failed to install app-debug. apk: Failure [INSTALL_FAILED_TEST_ONLY: installPackageLI]
Prometheus deployment
C language pointer and two-dimensional array
跨区域网络的通信学习静态路由
C language function
English translation Arabic - batch English translation Arabic tools free of charge
Article translation software - batch free translation software supports major translation interfaces