如何给printf在C中的内存地址 [英] How to printf a memory address in C
问题描述
我的code是:
#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);
我使用的终端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\n", &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\n", (void*)&A);
该标准要求的参数类型是无效*
为%P
说明符。一直以来,的printf
是一个可变参数函数,没有隐式转换无效*
从 T *
这将隐含发生在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中的参数应该是一个指针无效。指针的值是
转换为打印字符的序列,在一个
实现定义的方式。
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.
这篇关于如何给printf在C中的内存地址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!