0 c pointers double-pointer dereference
仅双指针存储指针的地址不是真的吗?然后如何存储整数地址?
{
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?
}
Run Code Online (Sandbox Code Playgroud)
至于您的问题,因为您ptr指向&a,那么做*ptr的结果与做的结果相同*(&a),&a即为您提供where 指向的值,即的值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
Run Code Online (Sandbox Code Playgroud)
之后*ptrptr == ptr,和**ptrptr == *ptr和**ptrptr == a。
从图形上可以看到以上内容
+ -------- + + ----- + + --- + | ptrptr | -> | ptr | -> | 一个| + -------- + + ----- + + --- +
| 归档时间: |
|
| 查看次数: |
58 次 |
| 最近记录: |