c - 双指针如何真正以这种方式表现?

标签 c pointers dereference double-pointer

不是双指针只存储指针的地址吗? 那么它如何存储整数地址?

{
    int **ptr,a;
    a = 10;
    ptr = &a; 

    printf("value of a = %d\n",*ptr);  //why it works?
    printf("value of a = %d\n",**ptr); //why it doesnt work?

}

最佳答案

至于你的问题,因为你让 ptr 指向 &a,那么 *ptr 会导致与 相同的结果code>*(&a) 为您提供 &a 指向的位置的值,即 a 的值。虽然它在语义上是不正确的,并且如果 int * 的大小(这是 *ptr 的实际大小)与 int 的大小不同,可能会导致其他问题(a 是什么)。

当您执行 **ptr 时,您将 a 的值视为指针,并取消引用它。由于 10 在现代 PC 上不太可能是有效指针,您将得到未定义的行为


你说“双指针存储指针的地址”,这是正确的。指向指针的指针可以存储指针的地址(指针)。但是&a不是指针的地址,而是非指针变量a的地址。

要使“双指针”(真正指向指针的指针)起作用,您需要类似的东西

int a = 10;
int *ptr = &a;  // Make ptr point to the variable a
int **ptrptr = &ptr;  // Make ptrptr point to the variable ptr

在此之后,*ptrptr == ptr**ptrptr == *ptr**ptrptr == a

从图形上看,上面的内容类似于

+--------+     +-----+     +---+
| ptrptr | --> | ptr | --> | a |
+--------+     +-----+     +---+

关于c - 双指针如何真正以这种方式表现?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55532899/

相关文章:

rust - 从 Option<Rc<RefCell<T>>> 解包并访问 T

c - 该算法存在一些缺陷,无法通过名为 "partly calculate A add B"的所有OJ测试

从二维数组到双指针的转换

在 C 中创建一个处理重定向和管道的 shell

c++ - Const 在模板函数参数列表中被忽略

iOS应用程序: incompatible pointer types

c - *(long *) 和 *(int*) 是什么意思?

Perl %{$var} 与 %$var

c - OpenSSL导致丢包?奇怪的CPU使用率

c# - 使用指针访问结构成员