简体   繁体   English

打印内存中变量的地址

[英]Print the address of a variable in memory

#include<stdio.h>
main() {
    int i=9;

    printf("\nAddress of i = %d", &i);
    printf("\nAddress of i = %x", &i);
    printf("\nAddress of i = %u", &i);
    printf("\nAddress of i = %p", &i);
    printf("\nValue of i = %d",i);
}

When I use %p I get: Value of i = 0xbfd08d5c 当我使用%p我得到: i值= 0xbfd08d5c
Other formats %d , %x , %u don't work. 其他格式%d%x%u不起作用。

In general, you are not allowed to use %d , %x , or %u for an address. 通常,不允许将%d%x%u用作地址。 You should use only %p - that is the only valid format to use for pointers. 您应该仅使用%p这是用于指针的唯一有效格式。

Moreover, since %p expects a void pointer, you need to add a cast to &i operation: 此外,由于%p需要空指针,因此您需要在&i操作中添加强制类型转换:

printf("\nAddress of i = %p", (void*)&i);

Although the code would work without a cast on most platforms, it is a good idea to add a cast to guarantee compatibility with platforms where a pointer to an int and a void pointer have different representations. 尽管代码在大多数平台上都不需要强制转换就可以工作,但是最好添加强制转换以保证与int指针和void指针具有不同表示形式的平台兼容。 I am not sure if there are any such platforms, but the standard does not prohibit them. 我不确定是否有这样的平台,但是该标准并未禁止它们。

address is a positive integer, therefore, using "%u" , ie, unsigned int, can print the correct address value. address是一个正整数,因此,使用“%u”,即unsigned int,可以打印正确的地址值。

ps, "%p" in hexadecimal format and "%u" in common decimal format. ps,十六进制格式为“%p”,普通十进制格式为“%u”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM