如何在C中打印内存地址

var*_*cle 21 c printf pointers memory-address unary-operator

我的代码是:

#include <stdio.h>
#include <string.h>

void main()
    {
    char string[10];
    int A = -73;
    unsigned int B = 31337;

    strcpy(string, "sample");

    // printing with different formats
    printf("[A] Dec: %d, Hex: %x, Unsigned: %u\n", A,A,A);
    printf("[B] Dec: %d, Hex: %x, Unsigned: %u\n", B,B,B);
    printf("[field width on B] 3: '%3u', 10: '%10u', '%08u'\n", B,B,B);

    // Example of unary address operator (dereferencing) and a %x
    // format string 
    printf("variable A is at address: %08x\n", &A);
Run Code Online (Sandbox Code Playgroud)

我在linux mint中使用终端编译,当我尝试使用gcc编译时,我收到以下错误消息:

basicStringFormatting.c: In function ‘main’:
basicStringFormatting.c:18:2: warning: format ‘%x’ expects argument
of type ‘unsigned int’, but argument 2 has type ‘int *’ [-Wformat=]
printf("variable A is at address: %08x\n", &A);
Run Code Online (Sandbox Code Playgroud)

我所要做的就是在变量A的内存中打印地址.

P.P*_*.P. 45

使用格式说明符%p:

printf("variable A is at address: %p\n", (void*)&A);
Run Code Online (Sandbox Code Playgroud)

该标准要求的参数是类型void*%p说明符.因为,printf是一个可变参数函数,没有隐式转换void *T *哪个会隐含发生在C.任何非可变参数的功能因此,需要演员.引用标准:

7.21.6格式化输入/输出功能(C11草案)

p参数应该是指向void的指针.指针的值以实现定义的方式转换为打印字符序列.

而你正在使用%x,它期望unsigned int&A为型int *.您可以从手册中了解printf的格式说明符.printf中的格式说明符不匹配会导致未定义的行为.

  • 转向`void*`的重要事情 (5认同)
  • 我在一个小应用程序中测试了带和不带强制转换的变量打印地址,但得到了相同的结果。但显然标准的声明( _p 参数应是指向 void_ 的指针)几乎没有留下解释的空间。谢谢。 (2认同)