如何在C中打印内存地址

我的代码是:

#include  #include  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); 

我在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); 

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

使用格式说明符%p

 printf("variable A is at address: %p\n", (void*)&A); 

该标准要求参数的类型为void* for %p说明符。 因为, printf是一个可变函数,所以没有从T *隐式转换为void * ,这对于C中的任何非变量函数都会隐式发生。因此,需要使用强制转换。 引用标准:

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

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

而您使用的是%x ,它需要unsigned int&A的类型为int * 。 您可以从手册中了解printf的格式说明符。 printf中的格式说明符不匹配会导致未定义的行为