当前位置:网站首页>Detailed explanation of C language pointer
Detailed explanation of C language pointer
2022-06-29 13:25:00 【Hua Weiyun】
In depth understanding of char * ,char ** ,char a[] ,char *a[]
1. The nature of arrays
An array is a collection of multiple elements , In memory, distributed in units connected by addresses , Therefore, the elements of different units can be accessed through their subscripts .
2. The pointer
Pointer is also a variable , Only its memory unit stores an address identifying other locations . Because the address is also an integer , stay 32 Under the platform , The default pointer is 32 position .
3. Pointer pointing
The direct meaning of pointing is the data type stored in other address units saved by pointer variables .
int *p; //p The data type in the memory unit where the address saved by the variable is integer float *q; // ............. floating-point Regardless of the data type pointed to , The pointer variable itself is always an integer , Because it saves the address .
4. A character array
It literally means array , The elements in the array are characters . exactly , This is its essential meaning .
char str[10]; // Defines an array of ten elements , The element type is character .C When a variable is defined in a language, it can be initialized .
char str[10] = {"hello"}; When the compiler encounters this sentence , Will be able to str From the first element in the array hello\0 Fill in one by one .
because C There is no real string type in the language , Strings can be represented by character arrays , Because its element addresses are continuous , That's enough .
C Language specifies that the array represents the first address of the memory location where the array is located , It's also str[0] The address of , namely str = &str[0];
in addition
printf("%s",str); Why can you output a string with the first address .
Because there is another key , stay C The essential representation of string constant in language is actually an address , This is a difficult problem for many beginners to understand .
give an example :
char *s ;s = "China"; Why can you assign a string to a pointer variable .
Isn't this type inconsistent
This is the key mentioned above .
C The compiler assigns a constant address to the language string , If “China”, Stored in memory 0x3000 0x3001 0x3002 0x3003 0x3004 0x3005 .
s = "China" , What do you mean ? by the way , Address .
In fact, the real meaning is s ="China" = 0x3000;
See clearly , You put China As a string , But the compiler sees it as an address 0x3000, That is, the essential expression of a string constant is the address of its first character .
s = 0x3000 This seems to be more intuitive . That's what it is. C The essence of pointer in language , He is a number , Only the compiler can understand that this number is an address , Not data .
So when printing strings , When we use different formatted output control words , Pointers have different meanings .
that %s , In fact, its principle is to output a string through the first address of the string ,printf("%s ", s); What passed to it was actually s The address of the saved string .
When we use %p When printing the address .
such as
#include <stdio.h> int main() { char *s; s = "hello"; printf("%p\n",s); return 0; }result :
00422020 You can see s = 0x00422020 , This is also "hello" The first address
therefore ,printf("%s","0x00422020"); It's also equivalent .
A character array :
char str[10] = "hello"; As I said before ,str = &str[0], Also equal to "hello" The first address .
therefore printf("%s",str); Essence is also printf("%s", Address );
C In language, the operation of a string is carried out through the first address of its storage unit in memory , This is the ultimate essence of strings .
5.char * And char a[]
char *s;char a[] ; It was said that a Represents the first address of the string , and s This pointer also holds the address of the string ( Actually, the first address ), That is, the address of the first character , The data in this address unit is a character ,
This is also related to s The point is char Agreement .
therefore Sure s = a;
however You can't a = s;
C The array name in the language can be copied to the pointer to represent the address , But it can't be assigned to the array name , It is a constant type , So it can't be modified .
Of course, you can do the same :
char a [ ] = "hello"; char *s =a; for(int i= 0; i < strlen(a) ; i++){ printf("%c", s[i]); // or printf("%c",*s++);} Character pointers can be used Indirect operator * Take its content , You can also use the subscript form of an array [ ], Array names can also be used * operation , Because it itself represents an address .
such as
printf("%c",*a);Will print out ‘h’
6.char * And char a[] The essential difference :
When defining char a[10] when , The compiler allocates ten units to the array , The data type of each cell is character .
Definition char *s when , This is a pointer variable , Only four bytes ,32 position , Used to save an address .
sizeof(a) = 10 ; sizeof(s) = ?Certainly 4 了 , Compiler allocation 4 Bytes 32 Bit space , The address will be saved in this space .
printf("%p",s);The said s The address stored in the unit of .
printf("%p",&s); This represents the address of the memory unit where the variable itself is located , Don't confuse .
Sum up in one sentence , Namely char *s Just a pointer variable that holds the first address of the string , char a[] Is a number of contiguous memory units , The elements in the cell are char .
The reason to use char * Can achieve char a[] The effect of , Or the essence of string , Address . That is, give you a string address , You can operate him at will , however ,char * and char a[] The essential properties of are different .
7.char ** And char *a[]
First look at
char *a[] ;because [] Has a higher priority than * therefore a The first and [] combination , He's also an array , The elements in the array are char * , As mentioned earlier char * It's a variable , Saved address .
char *a[] = {"China","French","America","German"}; Through this sentence, we can see , The elements in the array are strings , that sizeof(a) How much is? , One would think that five words account for all the bytes in memory 6+7+8+7 = 28;
But in fact sizeof(a) = 16;
Why? , I've already said that , The essence of a string constant is an address ,a The elements in the array are char * The pointer , Pointer variables take up four bytes , So the four elements are 16 The bytes
Take a look at the examples :
#include <stdio.h> int main() { char *a [] = {"China","French","America","German"}; printf("%p %p %p %p\n",a[0],a[1],a[2],a[3]); return 0; }You can see that the four elements in the array hold four memory addresses , These four addresses represent the first address of the four strings , Not the string itself .
therefore sizeof(a) Certainly 16 了 ..
Note that the four addresses are not contiguous , It is a compiler for "China",“French”,“America”,“German” The address of the allocated memory space , therefore , The four addresses are not associated .
#include <stdio.h> int main() { char *a [ ] = {"China","French","America","German"}; printf("%p %p %p %p\n",a[0],a[1],a[2],a[3]); // The address saved in the array element printf("%p %p %p %p\n",&a[0],&a[1],&a[2],&a[3]);// The address of the array element unit itself return 0; }You can see 0012FF38 0012FF3C 0012FF40 0012FF44, These four are the address of the element unit , Each address differs by four bytes , This is because each element is a pointer variable, accounting for four bytes .
char **s;char ** Is a secondary pointer , s Save first level pointer char * The address of , The second level pointer will not be discussed in detail here , To put it simply, the error prone point of the secondary pointer .
give an example :
char *a[] = {"China","French","America","German"}; char **s = a;Why can you put a Assign to s, Because the array name a Represents the first address of the memory unit of the array element , namely a = &a[0] = 0012FF38;
and 0x12FF38 namely a[0] What is kept in the is 00422FB8 , This address , 00422FB8 For the string "China" The first address .
*s = 00422FB8 = "China";So you can get through s operation a Data in
printf("%s",*s); printf("%s",a[0]); printf("%s",*a); It's all the same .
But pay attention to , You can't a = s, I've already said that ,a Is a constant .
Look at another fallible point :
char **s = "hello world"; This is wrong ,
because s The type is char ** and "hello world " The type is char *
Although they are all addresses , But the types of points are different , therefore , You can't do that .
Analyze from its essence ,“hello world”, Represents an address , such as 0x003001, The content in this address is ‘h’, by char type , and s Also save an address , The contents of this address (*s) yes char * , It's a pointer type , So the two types are different .
What if that's the case :
char **s; *s = "hello world"; It seems reasonable , There's no problem compiling , however printf("%s",*s), It will collapse ,
Let's consider it slowly .printf("%s",*s); when , First of all, there must be s Saved address , Then find... In this address char * The address of , namely *s;
give an example :
s = 0x1000; stay 0x1000 In the memory unit where it is located "hello world" The address of 0x003001 , *s = 0x003001;
such printf("%s",*s);
This will find 0x1000, And then find 0x003001;
If direct
char **s;*s = "hello world";s The variable holds an invalid random unavailable address , No one knows where it points ,*s The operation will crash .
So use char **s when , To assign it a memory address .
char **s ; s = (char **) malloc(sizeof(char**)); *s = "hello world"; such s Assigned an available address to , such as s = 0x412f;
And then in 0x412f Location in memory where , preservation "hello world" Value .
Again :
#include <stdio.h> void buf( char **s) { *s = "message"; } int main() { char *s ; buf(&s); printf("%s\n",s); } Simple usage of secondary pointer ., To put it bluntly , The secondary pointer stores the address of the primary pointer , Its type is pointer variable , The first level pointer stores the address of the memory unit where the data is located , Although they are all addresses , But the type is different .
The last show ,sizoof( The pointer ) The size of depends on the computer operating system , commonly 32 The memory size occupied by the bit operating system is 4,64 The size of the bit operating system pointer is 8.
char **s; *s = "hello world";In my ubuntu Print on printf("%s",*s), No breakdown .
边栏推荐
- 揭秘!付费会员制下的那些小心机!
- mysql调优
- C#线索二叉树的定义
- ZALSM_ EXCEL_ TO_ INTERNAL_ Solving the big problem of importing data from table
- CVPR 2022 | 未知目标检测模块STUD:学习视频中的未知目标
- Acwing game 57
- The imshow function of Matplotlib displays grayscale images. Vmin and vmax2 parameters should be set
- Leetcode game 299
- C语言的指针详解
- Aes-128-cbc-pkcs7padding encrypted PHP instance
猜你喜欢

QT signal and slot

C binary tree structure definition and node value addition

Pod security policy (PSP)

CVPR 2022 | 未知目标检测模块STUD:学习视频中的未知目标

Aes-128-cbc-pkcs7padding encrypted PHP instance

Proteus simulation of buck switching power supply based on 51 single chip microcomputer

Another "provincial capital university", coming!

OPC of Beifu twincat3_ UA communication test case
![Equidistant segmentation of surface rivers in ArcGIS [gradient coloring, pollutant diffusion]](/img/05/18fb41f78b9b57175d50dfece65535.png)
Equidistant segmentation of surface rivers in ArcGIS [gradient coloring, pollutant diffusion]

3D model downloading and animation control
随机推荐
力扣:合并两个有序链表
bind原理及模拟实现
C # clue binary tree through middle order traversal
CVPR2022 | 可精简域适应
开户可以在网上开么?能安全吗
Precautions for Beifu controller connecting Panasonic EtherCAT servo
C语言内存函数
leetcode 903. DI 序列的有效排列
PyGame accurately detects image collision
mysql调优
Memorized Function
服务器监控netdata面板配置邮件服务
QT signal and slot
C language simulation to realize all character functions
Equidistant segmentation of surface rivers in ArcGIS [gradient coloring, pollutant diffusion]
安装typescript环境并开启VSCode自动监视编译ts文件为js文件
Aes-128-cbc-pkcs7padding encrypted PHP instance
自主可控再下一城!首套国产ARTIQ架构量子计算测控系统发布
Check yaml file security configuration: kubesec
win32版俄罗斯方块(学习MFC必不可少)