当前位置:网站首页>C language beginner level - pointer explanation - paoding jieniu chapter
C language beginner level - pointer explanation - paoding jieniu chapter
2022-07-03 02:46:00 【Xiao Lu LC】
List of articles
I'm learning C In the process of language , Did you learn well before the chapter of pointer , When it comes to the pointer, I start to feel a little confused , And the pointer is very, very important , If you don't understand this chapter, it will affect your later study , It's going on C When the language is advanced, it will not be handy , This is what I did when I was studying , Now I'm interested in learning C Summarize the problems encountered in language , I hope it can help you .
1. What is the pointer ?
The pointer understands 2 A point :
- Pointer is ** The number of the smallest cell in memory **, That is to say Address
- The pointer in spoken English , Usually it means ** Pointer to the variable **, Is a variable used to store the memory address
summary : The pointer is the address , Pointer in spoken language usually refers to pointer variable .
We can also understand this :
First, let's understand what memory is , When we buy computers, we all hear that this memory is 8G Of , This memory is 16G Of . Memory, as the name suggests, is where data is stored , There's nothing to say about this , Now let's talk about how to manage such a large memory space ?
Memory space management :
Cut into memory units ——1byte( byte ).
The above figure basically illustrates the meaning of the first layer :
Pointer is ** The number of the smallest cell in memory **, That is to say Address .
#include <stdio.h>
int main()
{
int a = 10; //a Is an integer variable , Take up four bytes
return 0;
}
As you can see from the above example , An integer number 10 Occupy 4 Bytes , And the address is the address of the first byte .
Pointer to the variable
We can go through &( Take the address operator ) Take out the memory address of the variable , The address can be stored in a variable , This variable is the pointer variable .
#include <stdio.h>
int main()
{
int a = 10;// Open up a space in memory
int* p = &a;// Here we're looking at variables a, Take out its address , have access to & The operator .
//a Variable occupancy 4 Bytes of space , Here is the general a Of 4 The address of the first byte of a byte is stored in p Variable
// in ,p Is a pointer variable to .
return 0;
}
A pointer is essentially an address
The pointer in spoken English , It's actually a pointer variable , A pointer variable is a variable , The pointer variable is ** It's used to store the address ** A variable of
Small expansion : The numbers of these addresses do not need to be stored in the computer , They are generated by hardware , Just use direct access .
summary :
Pointer to the variable , The variable used to hold the address .( The values stored in the pointer are treated as addresses ).
The problem here is :
How big is a small unit ?(1 Bytes )
How to address ?
After careful calculation and weighing, we find that A byte gives a corresponding address It's more appropriate .
about 32 Bit machine , Suppose there is 32 Root address line , Then suppose that each address line generates a high level during addressing ( high voltage ) And low power
flat ( Low voltage ) Namely (1 perhaps 0);
that 32 The address generated by the root address line will be :
00000000 00000000 00000000 00000000
00000000 00000000 00000000 00000001
…
11111111 11111111 11111111 11111111
There is 2 Of 32 The next address .
Each address identifies a byte , Then we can give (2^32Byte == 2^32/1024KB ==
232/1024/1024MB==232/1024/1024/1024GB == 4GB) 4G Address when free .
that 64 The same is true for bit machines .
Here we understand :
stay 32 On the machine , The address is 32 individual 0 perhaps 1 Make up a binary sequence , Then the address has to be 4 Bytes of space to store , therefore
The size of a pointer variable should be 4 Bytes .
Well, if it's in 64 On the bit machine , If there is 64 Address lines , The size of that pointer variable is 8 Bytes , To store in a place
site .
summary :
Pointer variables are used to store addresses , An address is a unique identifier of an address space .
The size of the pointer is 32 Bit platform is 4 Bytes , stay 64 Bit platform is 8 Bytes .
2. Pointers and pointer types
Here we are discussing : The type of pointer
We all know , There are different types of variables , plastic , Floating point, etc . Does the pointer have a type ?
Accurately speaking : yes , we have .
When there is such code :
int num = 10;
p = #
To put &num(num The address of ) Save to p in , We know p It's a pointer variable , What is its type ?
We give the pointer variable the corresponding type .
char *pc = NULL;
int *pi = NULL;
short *ps = NULL;
long *pl = NULL;
float *pf = NULL;
double *pd = NULL;
Here you can see , The way pointers are defined is : type + * .
Actually :
char A pointer to a type is to hold char The address of a type variable .
short A pointer to a type is to hold short The address of a type variable .
int* A pointer to a type is to hold int The address of a type variable .**
What is the meaning of pointer type ?
Now let's see how many bytes different pointer variables occupy ?
#include <stdio.h>
int main()
{
char* pc = NULL;
short* ps = NULL;
int* pi = NULL;
double* pd = NULL;
printf("%u\n", sizeof(pc));
printf("%u\n", sizeof(ps));
printf("%u\n", sizeof(pc));
printf("%u\n", sizeof(pd));
return 0;
}
We can see that everything printed out is 8 Bytes , Because my computer is 64 Bit , Yes 64 Root address line , Capable of producing 64 individual 0 or 1, So we need to 8 Bytes to store ( One byte can store 8 A digital , That is, a byte storage 8 A binary sequence ).
If your computer is 32 Bit , Then what should be printed is 4 Bytes , Empathy 32 Binary sequences require 4 Bytes to store .
Let's think about a problem : Different types of pointer variables occupy the same storage , So what's the use of classification ?
// The meaning of pointer type
// 0 1 2 3 1 4 5 6 7 8 9 a b c d e f Hexadecimal number
#include <stdio.h>
int main()
{
int a = 0x11223344; // This hexadecimal array needs 4 Bytes
int* pa = &a;
*pa = 0;
return 0;
}
From this example, we can see that ,int* This pointer variable can operate 4 Bytes .
// The meaning of pointer type
// 0 1 2 3 1 4 5 6 7 8 9 a b c d e f Hexadecimal number
#include <stdio.h>
int main()
{
int a = 0x11223344; // This hexadecimal array needs 4 Bytes
char* pa = &a;
*pa = 0;
return 0;
}
Now we change the pointer type to char*, You can see that now only one byte can be operated .
summary :
The type of pointer variable determines how many bytes can be accessed when the pointer is dereferenced ,
Integer pointers can only access 4 Bytes ,
Character pointers can only access 1 Bytes .
Extend to other types .
2.1 The pointer + - Integers
Let me take a look at a code
#include <stdio.h>
int main()
{
int a = 0x11223344;
int* pa = &a;
char* pc = &a;
printf("pa = %p\n", pa);
printf("pa = %p\n", pa+1);
printf("pc = %p\n", pc);
printf("pc = %p\n", pc+1);
return 0;
}
From the example above, we can see that int Type pointer +1 Skip the 4 An address , That is to skip 4 Bytes , and char Type pointer +1 Skip the 1 Bytes .
summary :
The type of pointer determines the pointer +1 or -1 During operation , Skip a few bytes .
Determines the step size of the pointer .
2.2 Dereference of pointer
#include <stdio.h>
int main()
{
int n = 0x11223344;
char *pc = (char *)&n;
int *pi = &n;
*pc = 0; // Focus on observing memory changes during debugging .
*pi = 0; // Focus on observing memory changes during debugging .
return 0;
}
summary :
The type of pointer determines , How much authority does it have to dereference a pointer ( Can manipulate a few bytes ).
such as : char* Only one byte can be accessed by dereferencing the pointer of , and int* Four bytes can be accessed by dereferencing the pointer of .
3. Wild pointer
Concept : The position of the pointer is unknown ( Random 、 incorrect 、 There is no definite limit to )
3.1 The cause of the wild pointer
- Pointer not initialized
#include <stdio.h>
int main()
{
int *p;// Local variable pointer not initialized , The default value is random
// A local variable that is not initialized is a random value
*p = 20; // Illegal access to memory , there p It's a wild pointer
return 0;
}
- Pointer cross boundary access
#include <stdio.h>
int main()
{
int arr[10] = {
0};
int *p = arr;
int i = 0;
for(i=0; i<=11; i++)
{
// When the pointer points to an array arr The scope of time ,p It's a wild pointer
*(p++) = i;
}
return 0;
}
- The space that the pointer points to is released
#include <stdio.h>
int* test()
{
int a = 0;
return &a;
}
int mian()
{
int* p = test();
return 0;
}
We can see this code , After the function is used , Space is released , But the pointer in the main function still remembers the address , Then it becomes a wild pointer when used .
3.2 How to avoid wild pointer
- Pointer initialization
int a = 0;
int* p = &a;
- Watch out for the pointer
- Pointer to space release even if set to NULL
if(p != NULL) // This can effectively prevent the generation of wild pointers
{
*p = 100;
}
- Avoid returning the address of a local variable
- Check the validity of the pointer before using it
4. Pointer arithmetic
The pointer ± Integers
The pointer - The pointer
The relational operation of pointers
4.1 The pointer ± Integers
#define N_VALUES 5
float values[N_VALUES];
float *vp;
// The pointer +- Integers ; The relational operation of pointers
for (vp = &values[0]; vp < &values[N_VALUES];)
{
*vp++ = 0;
}
Join us to create a 10 An integer array of elements , And initialize it all to 1, What are we going to do ?
The first is the first , Array subscript writing :
#include <stdio.h>
int main()
{
int arr[10] = {
0 };
int i = 0;
int sz = sizeof(arr) / sizeof(arr[0]); // Count the number of elements
for (i=0;i<sz;i++)
{
arr[i] = 1;
}
return 0;
}
So how should we write in the way of pointer ?
#include <stdio.h>
int main()
{
int arr[10] = {
0 };
int i = 0;
int sz = sizeof(arr) / sizeof(arr[0]); // Count the number of elements
int* p = arr;
for (i = 0;i < sz;i++)
{
*(p + i) = 1;
}
return 0;
}
4.2 The pointer - The pointer
I don't say much nonsense , Go straight to the code
#include <stdio.h>
int main()
{
int arr[10] = {
0 };
printf("%d\n", &arr[9] - &arr[0]);
return 0;
}
Why is that ?
summary :
The pointer - What the pointer gets is the number of elements between the pointer
Be careful :
Not all pointers can be subtracted ;
Pointing to the same space 2 A pointer to subtract ! Otherwise it will be meaningless !
actual combat :
We need to calculate the length of the string , How to use the pointer ?
Then we just need to take To the address of the first element and the address of the last element The address is done .
#include <stdio.h>
int my_strlen(char* str)
{
char* start = str;
while (*str != '\0')
{
str++;
}
return (str - start);
}
int main()
{
int len = my_strlen("abcdef");
printf("%d", len);
}
4.3 The relational operation of pointers
The following is a code to initialize the array
for(vp = &values[N_VALUES]; vp > &values[0];)
{
*--vp = 0;
}
Code simplification , This modifies the code as follows
for(vp = &values[N_VALUES-1]; vp >= &values[0];vp--)
{
*vp = 0;
}
In fact, most compilers can successfully complete the task , However, we should avoid writing like this , Because the standard does not guarantee that it is feasible .
The standard stipulates :
Allows a pointer to an array element to be compared with a pointer to the memory location after the last element of the array , But not allowed with
Compare the pointer to the memory location before the first element .
5. Pointers and arrays
Array : A collection of elements of the same type
Pointer to the variable : It's a variable , It's the address
What do they have to do with it ?
Go straight to the code :
#include <stdio.h>
int main()
{
int arr[10] = {
0 };
//arr It's the first element address
//&arr[0]
int* p = arr;
// Access pointers through arrays
return 0;
}
#include <stdio.h>
int main()
{
int arr[10] = {
1,2,3,4,5,6,7,8,9,0 };
printf("%p\n", arr);
printf("%p\n", &arr[0]);
return 0;
}
It can be seen that the array name and the address of the first element of the array are the same .
Conclusion : The array name represents the address of the first element of the array .
So it's feasible to write code like this :
int arr[10] = {
1,2,3,4,5,6,7,8,9,0};
int *p = arr;//p It stores the address of the first element of the array
Since you can store the array name as an address in a pointer , It is possible for us to use pointers to access a .
for example :
#include <stdio.h>
int main()
{
int arr[] = {
1,2,3,4,5,6,7,8,9,0};
int *p = arr; // The pointer holds the address of the first element of the array
int sz = sizeof(arr)/sizeof(arr[0]);
for(i=0; i<sz; i++)
{
printf("&arr[%d] = %p <====> p+%d = %p\n", i, &arr[i], i, p+i);
}
return 0;
}
therefore p+i It's actually an array arr Subscript to be i The address of .
Then we can access the array directly through the pointer .
as follows :
int main()
{
int arr[] = {
1, 2, 3, 4, 5, 6, 7, 8, 9, 0 };
int* p = arr; // The pointer holds the address of the first element of the array
int sz = sizeof(arr) / sizeof(arr[0]);
int i = 0;
for (i = 0; i < sz; i++)
{
printf("%d ", *(p + i));
}
return 0;
}
So these ways of writing are Equivalent Of
printf("%d ", arr[ i ]);
printf("%d", *(p+i));
printf("%d", *(arr+i));
6. The secondary pointer
Pointer variables are also variables , If it's a variable, it has an address , Where is the address of the pointer variable stored ?
This is about to mention the secondary pointer
The following code is the first level pointer
#include <stdio.h>
int main()
{
int a = 0;
int* pa = &a; //pa Is a pointer variable , First level pointer variable
*pa = 20;
printf("%d\n",a);
}
The secondary pointer :
#include <stdio.h>
int main()
{
int a = 0;
int* pa = &a; //pa Is a pointer variable , First level pointer variable
int** ppa=&pa; // ppa It's a secondary pointer
**ppa = 20;
//*pa = 20;
printf("%d\n",a);
}
So how to understand the two asterisks ?
For the second level pointer
Operation yes :
*ppa Through to ppa Dereference the address in , What you find in this way is pa , *ppa In fact, what I visited was pa .
int b = 20;
*ppa = &b;// Equivalent to pa = &b;
**ppa Through the first *ppa find pa , Then on pa Dereference : *pa , What we found was a .
**ppa = 30;
// Equivalent to *pa = 30;
// Equivalent to a = 30;
summary :
The second level pointer variable is used to store the address of the first level pointer variable
7. Pointer array
Pointer array is a pointer or an array ?
answer : It's an array . Is an array of pointers .
#include <stdio.h>
int main()
{
int a = 10;
int b = 20;
int c = 30;
int arr[10];
int* pa = &a;
int* pb = &b;
int* pc = &c;
//parr It's an array of pointers
// Pointer array
int* parr[10] = {
&a,&b,&c};
int i = 0;
for (i = 0;i < 3;i++)
{
printf("%d", *(parr[i]));
}
return 0;
}
Understand this pointer array, you can use the pointer array to simulate a two-dimensional array , Give it a try !
Summing up difficulties , If it's useful to you, just pay attention !
Keep updating !
边栏推荐
- What does it mean when lambda is not entered?
- 简单理解svg
- Wechat - developed by wechat official account Net core access
- 定了,就选它
- C语言中左值和右值的区别
- Gbase 8C system table PG_ cast
- Gbase 8C trigger (II)
- [hcia]no.15 communication between VLANs
- SqlServer行转列PIVOT
- The Linux server needs to install the agent software EPS (agent) database
猜你喜欢
Random Shuffle attention
Joking about Domain Driven Design (III) -- Dilemma
HW initial preparation
Add MDF database file to SQL Server database, and the error is reported
《MATLAB 神经网络43个案例分析》:第43章 神经网络高效编程技巧——基于MATLAB R2012b新版本特性的探讨
Pytest (6) -fixture (Firmware)
Check log4j problems using stain analysis
How to change the panet layer in yolov5 to bifpn
A2L file parsing based on CAN bus (2)
Principle and application of database
随机推荐
Serious security vulnerabilities reported by moxa mxview network management software
Gbase 8C system table PG_ class
Why choose a frame? What frame to choose
从C到Capable-----利用指针作为函数参数求字符串是否为回文字符
How to change the panet layer in yolov5 to bifpn
Packing and unpacking of JS
Classes and objects - initialization and cleanup of objects - constructor call rules
Interview stereotyped version
The core idea of performance optimization, dry goods sharing
Basic operation of binary tree (C language version)
面试项目技术栈总结
Concrete CMS vulnerability
《MATLAB 神经网络43个案例分析》:第43章 神经网络高效编程技巧——基于MATLAB R2012b新版本特性的探讨
Matlab tips (24) RBF, GRNN, PNN neural network
Can netstat still play like this?
tensorflow转pytorch笔记;tf.gather_nd(x,y)转pytorch
A2L file parsing based on CAN bus (2)
Didi programmers are despised by relatives: an annual salary of 800000 is not as good as two teachers
The Linux server needs to install the agent software EPS (agent) database
HW-初始准备