c - 为什么这个 *ptr 不给出存储在 ptr 变量中包含的内存地址处的实际值?

标签 c pointers printf format-specifiers conversion-specifier

这是一个关于指针的基本 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,不是吗?因为 * 给出了存储在其操作数中存储的内存地址处的实际值,对吗? 我错过了什么?

最佳答案

1420HEX 值。

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/

相关文章:

c - 使用宏与其扩展之间的区别

c - 由主母管控制的多叉

c++ - 直接从指针/地址访问数组的元素

c - 用指针打印

c - mips-openwrt-linux-gcc : unrecognized option '-rpath-link'

C 打印一个没有值(value)的字符

c - 下面如何进行多维数组的指针运算?

c - 尝试释放时指针地址无效

c stdout 打印没有换行?

c - 如何打印嵌入空值的字符串,以便用 "(null)"替换 '\0'