在下面的代码中,我将变量设置var为 20,然后将指针ptr设置为var. 然后该指针ptrptr保存了该指针的内存地址ptr。
#include <stdio.h>
void pointers()
{
int var = 20;
int* ptr;
ptr = &var;
int *ptrptr = ptr;
printf("Value at ptrptr[0] = %d \n", ptrptr[0]);
}
// Driver program
int main()
{
pointers();
return 0;
}
Run Code Online (Sandbox Code Playgroud)
输出:
Value at ptrptr[0] = 20
Run Code Online (Sandbox Code Playgroud)
为什么ptrptr[0]返回存储的值val,而不是指针的内存地址ptr。
我认为索引运算符[]返回该值存储的值。
我希望这是一个例子,可以更清楚地说明发生了什么。
#include <stdio.h>
int main()
{
int var = 20;
int *ptr = &var;
int *ptr2 = ptr;
printf("the value of the variable var is %d\n", var);
printf("the address of the variable var is %p\n\n", &var);
printf("the value of the pointer ptr is %p\n", ptr);
printf("the value pointed to by ptr is %d\n", *ptr);
printf("or, stated another way, it's %d\n\n", ptr[0]);
printf("the value of the pointer ptr2 is %p\n", ptr2);
printf("the value pointed to by ptr2 is %d\n", *ptr2);
}
Run Code Online (Sandbox Code Playgroud)
在我的机器上打印:
the value of the variable var is 20
the address of the variable var is 0x7ffeed56992c
the value of the pointer ptr is 0x7ffeed56992c
the value pointed to by ptr is 20
or, stated another way, it's 20
the value of the pointer ptr2 is 0x7ffeed56992c
the value pointed to by ptr2 is 20
Run Code Online (Sandbox Code Playgroud)
由于ptr和ptr2具有相同的类型 ( int *),并且由于它们拥有相同的指针值(因为我们说过ptr2 = ptr),因此它们的行为相同。
并且由于 C 中的“数组和指针之间的对应关系”,*ptr与ptr[0]. 两个表达式都会产生 指向的值ptr。
如果您的目的ptrptr是让它成为一个指向指针的指针,那么下面是该问题的说明。由于ptrptr是一个二级指针,它指向的值实际上是另一个指针,所以你必须非常仔细地考虑它。
int **ptrptr = &ptr;
printf("the value of the pointer ptrptr is %p\n", ptrptr);
printf("the value pointed to by ptrptr is %p\n", *ptrptr);
printf("and the value pointed to by that pointer is %d\n", **ptrptr);
Run Code Online (Sandbox Code Playgroud)
这还打印:
the value of the pointer ptrptr is 0x7ffeed569920
the value pointed to by ptrptr is 0x7ffeed56992c
and the value pointed to by that pointer is 20
Run Code Online (Sandbox Code Playgroud)