Excerpt from: "Introduction to C Language" http://c.biancheng.net/c/
A pointer can point to a common type of data, such as int, double, char, etc., or it can point to a pointer type of data, such as int *, double *, char *, etc.
If one pointer points to another pointer, we call it 二级指针
, or 指向指针的指针
.
Suppose there is a variable a of type int, p1 is a pointer variable pointing to a, and p2 is a pointer variable pointing to p1. Their relationship is shown in the following figure:
Convert this relationship into C language code:
int a =100;
int *p1 = &a;
int **p2 = &p1;
A pointer variable is also a kind of variable, which also takes up storage space, and can also be used to &
obtain its address. The C language does not limit the number of pointer levels. Each time a pointer is added, an asterisk must be added when defining a pointer variable *
. p1 is a first-level pointer, which points to common types of data, and there is one when it is defined *
; p2 is a second-level pointer, which points to a first-level pointer p1, and there are two when it is defined *
.
If we want to define another three-level pointer p3, let it point to p2, then we can write:
int ***p3 = &p2;
The four-level pointer is similarly true:
int ****p4 = &p3;
In actual development, first-level pointers and second-level pointers are often used, and high-level pointers are hardly used.
When you want to get the data pointed to by the pointer, add a * to the first-level pointer, add two * to the second-level pointer, add three * to the third-level pointer, and so on, please see the code:
#include <stdio.h>
int main(){
int a =100;
int *p1 = &a;
int **p2 = &p1;
int ***p3 = &p2;
printf("%d, %d, %d, %d\n", a, *p1, **p2, ***p3);
printf("&p2 = %#X, p3 = %#X\n", &p2, p3);
printf("&p1 = %#X, p2 = %#X, *p3 = %#X\n", &p1, p2, *p3);
printf(" &a = %#X, p1 = %#X, *p2 = %#X, **p3 = %#X\n", &a, p1, *p2, **p3);
return 0;
}
operation result:
100, 100, 100, 100
&p2 = 0X28FF3C, p3 = 0X28FF3C
&p1 = 0X28FF40, p2 = 0X28FF40, *p3 = 0X28FF40
&a = 0X28FF44, p1 = 0X28FF44, *p2 = 0X28FF44, **p3 = 0X28FF44
Take the three-level pointer p3 as an example to analyze the above code. ***p3
Is equivalent to *(*(*p3))
. *p3
Get is p2
of value, that p1
address; *(*p3)
get is p1
of value, that a
address; after three after the operation, "value" *(*(*p3))
is derived a
value.
Assuming that the addresses of a, p1, p2, and p3 are 0X00A0, 0X1000, 0X2000, 0X3000, the relationship between them can be described by the following figure:
Inside the box is the value of the variable itself, and below the box is the address of the variable.