如何在C中打印内存地址 [英] How to printf a memory address in C
问题描述
我的代码是:
#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
", A,A,A);
printf("[B] Dec: %d, Hex: %x, Unsigned: %u
", B,B,B);
printf("[field width on B] 3: '%3u', 10: '%10u', '%08u'
", B,B,B);
// Example of unary address operator (dereferencing) and a %x
// format string
printf("variable A is at address: %08x
", &A);
我在 linux mint 中使用终端进行编译,当我尝试使用 gcc 进行编译时,我收到以下错误消息:
I am using the terminal in linux mint to compile, and when I try to compile using gcc I get the following error message:
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
", &A);
我要做的就是打印变量 A 在内存中的地址.
All I am trying to do is print the address in memory of the variable A.
推荐答案
使用格式说明符 %p
:
printf("variable A is at address: %p
", (void*)&A);
<小时>
对于%p
说明符,标准要求参数的类型为void*
.因为 printf
是一个可变参数函数,所以没有从 T *
到 void *
的隐式转换,这对于任何非可变参数函数在C. 因此,需要演员阵容.引用标准:
The standard requires that the argument is of type void*
for %p
specifier. Since, printf
is a variadic function, there's no implicit conversion to void *
from T *
which would happen implicitly for any non-variadic functions in C. Hence, the cast is required. To quote the standard:
7.21.6 格式化输入/输出函数(C11 草案)
p 参数应该是一个指向 void 的指针.指针的值为转换为一系列打印字符,在一个实现定义的方式.
p The argument shall be a pointer to void. The value of the pointer is converted to a sequence of printing characters, in an implementation-defined manner.
而您使用的是 %x
,它需要 unsigned int
而 &A
是 int *
类型>.您可以阅读手册中printf的格式说明符.printf 中的格式说明符不匹配导致未定义行为.
Whereas you are using %x
, which expects unsigned int
whereas &A
is of type int *
. You can read about format specifiers for printf from the manual. Format specifier mismatch in printf leads to undefined behaviour.
这篇关于如何在C中打印内存地址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!