gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 05:47:50 24 4
gpt4 key购买 nike

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

{
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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com