大家好,有人可以解释一下为什么在声明指向指针的指针时我们需要使用 **
为什么我们不能只使用单个 *
将指针指向另一个指针或者是这只是一个语法相关的问题,例如
int main()
{
int a=5,*b,*c;
b=&a;
c=&b //Why cant this simply doesn't make c point to memory location of b with the above pointer declaration why is there a need to declare c as **c
}
最佳答案
使用以下代码:
int a=5,*b,**c;
b=&a;
c=&b;
我们有:
+---+
a | 5 | <-- value
+---+
|100| <-- address
+---+
+---+
*b |100| <-- value
+---+
|200| <-- address
+---+
+---+
**c |200| <-- value
+---+
|300| <-- address
+---+
当你把a的地址存入b时,b的值就是a的地址。但是 b 有它自己的地址 (200)。 c 可以存储 b 的地址作为它的值。但是 c 也有它自己的地址 (300)。
printf("%x", &c);
会给你:300
引用 *c 会让你下降“1 级”并给你 100(获取地址 200 的值)
Deferencing **c 会让你再下降 1 级并给你 5(获取地址 100 的值)
如果您尝试使用 *c 而不是 **c 来保存 *b,您如何能够一直顺从到值 5?
在编译器上测试代码:
printf("Address of a: %x\n", &a);
printf("Address of b: %x\n", &b);
printf("Address of c: %x\n", &c);
printf("Value of a: %d\n", a);
printf("Value of b: %x\n", b);
printf("Value of c: %x\n", c);
输出:
Address of a: 28ff44
Address of b: 28ff40
Address of c: 28ff3c
Value of a: 5
Value of b: 28ff44
Value of c: 28ff40
关于c++ - 指向指针的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27119944/