所以我一直在学习如何使用指针,这个简单的程序无法运行,我无法弄清楚出了什么问题我认为问题在于这行代码:
printf("Address of pointer variable = %x n",pointer_p);
我也尝试了printf("Address of pointer variable = %x n",&pointer_p);
仍然没有结果。
#include <stdio.h>
#include <stdlib.h>
int main() {
int val = 30;
int *pointer_p;
pointer_p = &val;
//shows the address of val (hexadecimal)
printf("Address of val = %xn", &val);
printf("Address of pointer variable = %xn", pointer_p);
//shows the value of this address
printf("Value of pointer = %dn", *pointer_p);
return 0;
}
要打印任何类型的地址,您必须使用 %p
并将指针投射到 void*
:
printf("Address where pointer is pointing = %pn", (void*) pointer_p);
printf("Address of pointer variable = %pn", (void*) &pointer_p);
请参阅 printf 文档
请记住,pointer_p
会返回它指向的地址。如果你想要变量的地址,你必须使用&pointer_p
.请参阅的 printf
以上。
要打印出pointer_p的地址(不是 val 的地址,它是 pointer_p 的值(:
printf("Address of pointer variable = %p n", (void *)&pointer_p);
您使用了错误的格式说明符。
使用 %p
而不是像这样%x
:
printf("Adress pointed to = %p n", pointer_p);
printf("Adress of pointer = %p n", &pointer_p);
这是一个可能有用的链接。