这是一个关于指针的基本 C 程序:
#include <stdio.h>
int main() {
int variable = 20;
int *pointerToVariable;
pointerToVariable = &variable;
printf("Address of variable: %x\n", &variable);
printf("Address of variable: %x\n", pointerToVariable);
printf("Address of variable: %x\n", *pointerToVariable); // * is the DEREFERENCING OPERATOR/INDIRECTION OPERATOR in C.
//It gives the value stored at the memory address
//stored in the variable which is its operand.
getchar();
return 0;
}
这会产生以下输出:
Address of variable: 8ffbe4
Address of variable: 8ffbe4
Address of variable: 14
但是*pointerToVariable
应该打印20,不是吗?因为 *
给出了存储在其操作数中存储的内存地址处的实际值,对吗?
我错过了什么?
最佳答案
14
是 20
的 HEX
值。
将 printf
格式说明符更改为 %d
而不是 %x
,以将 20
作为输出
printf("Address of variable: %d\n", *pointerToVariable);
此外,指针的正确格式说明符是 %p
,因此
printf("Address of variable: %x\n", pointerToVariable);
必须是
printf("Address of variable: %p\n", (void *)pointerToVariable);
关于c - 为什么这个 *ptr 不给出存储在 ptr 变量中包含的内存地址处的实际值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43109911/