指向指针的指针

Pointers to pointer

本文关键字:指针      更新时间:2023-10-16

大家好,有人可以解释为什么在声明指向指针的指针时我们需要使用 **为什么我们不能只使用单个*将指针指向另一个指针,或者这只是一个与语法相关的问题,例如

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 的值)

引用 **c 将使您再降低 1 级并给您 5(获取地址 100 的值)


如果您尝试使用 *c 而不是 **c 来保持 *b,您如何能够一直顺从以达到值 5?

在编译器上测试代码:

printf("Address of a: %xn", &a);
printf("Address of b: %xn", &b);
printf("Address of c: %xn", &c);
printf("Value of a: %dn", a);            
printf("Value of b: %xn", b);  
printf("Value of c: %xn", 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

在这种情况下

int main()
{
    int a=5,*b,*c;
    b=&a;
    c=&b;
}

这里的b指向ac指向b。这是您在评论中评论的内容。

C 仍然指向 B 的内存位置。

问题是:当你取消引用b*b = a = 5 .
但是当你取消引用c*c = b = &a.因此,当您取消引用c输出将是 a 的地址而不是变量 a 的值

PS :编译代码时,您将面临此警告warning: assignment from incompatible pointer type

每个间接寻址级别都需要一个级别的取消引用。所以对于:

T*** x = ...;

您将需要:

***x

T&.

如果您有指向指针的指针并将其保存在:

T* x = ...;
T* y = &x;

这意味着*ptr会导致T&,而它实际上会导致另一种T*

你的答案只在你的问题中。

  1. pointer变量,使用*
  2. 变量pointers to pointer,使用 **

详:

**不是运营商。 它是**的组合。在案例 2.根据您的术语,您可以想到

only single * to point a pointer to another pointer 

int * to an inother int * ==> int **

编辑:

根据您的代码

int main()
{
    int a=5,*b,*c;
    b=&a;
    c=&b;
}
  1. b是指向int的指针。您可以将int的地址存储在那里,a是一个int。完善。
  2. c 是指向 int 的指针。您可以将int的地址存储在那里,b是指向int的指针。不接受。

要使第 2 点正常工作,您需要将c声明为指向int *的指针,对吗?相同的表示法是 int ** .

这是另一种思考指针到指针的方法:想象一下它在内存中是如何工作的。 这里有一个小片段来说明我的意思:

int TheInteger = 123;
int *p = &TheInteger;
int **pp = &p;
printf("The value at memory location &pp (0x%x) is 0x%x (pp).  This value (which we assigned as &p (0x%x) is 0x%x (p).  This value, in turn, we assign as &TheInegeter (0x%x) points to the 'instance' of TheInteger, which is %d", &pp, pp, &p, p, &TheInteger, TheInteger);

其输出将是:

The value at memory location &pp (0x657e588) is 0x657e594 (pp).  This value (which we assigned as &p (0x657e594) is 0x657e5a0 (p).  This value, in turn, we assign as &TheInegeter (0x657e5a0) points to the 'instance' of TheInteger, which is 123

现在,回到最初的问题,当您设置变量的值是指针到指针时,您不能将变量声明为指针。 换句话说,在您的示例中,您将"b"设置为指向 -- 的指针,因此,您无法告诉编译器"c"只是一个指针,然后尝试将其设置为编译器知道是指针到指针的值。