c语言指向指针的指针
Pointers are used to store the address of other variables of similar datatype. But if you want to store the address of a pointer variable, then you again need a pointer to store it. Thus, when one pointer variable stores the address of another pointer variable, it is known as Pointer to Pointer variable or Double Pointer.
指针用于存储类似数据类型的其他变量的地址。 但是,如果要存储指针变量的地址,则再次需要一个指针来存储它。 因此,当一个指针变量存储另一个指针变量的地址时,称为指针到指针变量或双指针 。
Syntax:
句法:
int **p1;
Here, we have used two indirection operator(*
) which stores and points to the address of a pointer variable i.e, int *
. If we want to store the address of this (double pointer) variable p1
, then the syntax would become:
在这里,我们使用了两个间接运算符( *
),它们存储并指向指针变量即int *
的地址。 如果我们要存储此(双指针)变量p1
的地址,则语法将变为:
int ***p2
简单的程序,将指针表示为指针 (Simple program to represent Pointer to a Pointer)
#include <stdio.h>
int main() {
int a = 10;
int *p1; //this can store the address of variable a
int **p2;
/*
this can store the address of pointer variable p1 only.
It cannot store the address of variable 'a'
*/
p1 = &a;
p2 = &p1;
printf("Address of a = %u\n", &a);
printf("Address of p1 = %u\n", &p1);
printf("Address of p2 = %u\n\n", &p2);
// below print statement will give the address of 'a'
printf("Value at the address stored by p2 = %u\n", *p2);
printf("Value at the address stored by p1 = %d\n\n", *p1);
printf("Value of **p2 = %d\n", **p2); //read this *(*p2)
/*
This is not allowed, it will give a compile time error-
p2 = &a;
printf("%u", p2);
*/
return 0;
}
Address of a = 2686724 Address of p1 = 2686728 Address of p2 = 2686732 Value at the address stored by p2 = 2686724 Value at the address stored by p1 = 10 Value of **p2 = 10
a的地址= 2686724 p1的地址= 2686728 p2的地址= 2686732 p2存储的地址的值= 2686724 p1存储的地址的值= 10 ** p2 = 10的值
以上程序说明 (Explanation of the above program)
p1
pointer variable can only hold the address of the variablea
(i.e Number of indirection operator(*)-1 variable). Similarly,p2
variable can only hold the address of variablep1
. It cannot hold the address of variablea
.p1
指针变量只能保存变量a
的地址(即,间接操作符(*)-1的数量)。 同样,p2
变量只能保存变量p1
的地址。 它不能保存变量a
的地址。*p2
gives us the value at an address stored by thep2
pointer.p2
stores the address ofp1
pointer and value at the address ofp1
is the address of variablea
. Thus,*p2
prints address ofa
.*p2
给我们p2
指针存储的地址处的值。p2
存储p1
指针的地址,并且p1
地址处的值是变量a
的地址。 因此,*p2
打印解决的a
。**p2
can be read as*(*p2)
. Hence, it gives us the value stored at the address*p2
. From above statement, you know*p2
means the address of variable a. Hence, the value at the address*p2
is 10. Thus,**p2
prints10
.**p2
可以读为*(*p2)
。 因此,它为我们提供了存储在地址*p2
处的值。 通过上面的语句,您知道*p2
表示变量a的地址。 因此,地址*p2
值为10。因此,**p2
打印10
。
c语言指向指针的指针