为什么格式字符串中 %p 和 %x 的格式不同?
Why is the format of %p and %x different in a format string?
打印十六进制值(%x
)和地址(%p
)时,格式略有不同。在十六进制值的情况下,打印值不以0x
开头:
int main()
{
int x = 0x1234;
printf("Value of x: %x\n", x);
printf("Address of x: %p\n", (void*)&x);
}
产量(gcc):
Value of x: 1234
Address of x: 0xffb0fbfc
为什么在地址的情况下 0x
强加给你?
我想这归结为标准。
如果我愿意,在没有 0x
的情况下打印地址的正确方法是什么? %p
不只是 %x
加上 0x
对吧?
p
The argument shall be a pointer to void. The value of the pointer is
converted to a sequence of printable characters, in an
implementation-defined manner.
%p
的输出格式是特定于实现的。并非每个 C 实现都在地址大小与 int
相同的机器上。 intptr_t
来自 <stdint.h>
The %p is not only a %x with an added 0x right?
否.. %p
期望参数为 (void *) 类型并打印出地址。
而 %x
将无符号整数转换为无符号十六进制并打印出结果。
%p
所做的是实现定义,但标准只是说 %p
期望 void*
参数,否则行为未定义。
MSVC 不会强制我使用“0x”前缀,但您可以选择像这样删除它:
#include <stdio.h>
#include <string.h>
int main(void) {
int x = 123;
char hexstr[20];
sprintf(hexstr,"%p", (void*)&x);
if (strstr(hexstr,"0x") == hexstr)
printf ("%s\n", hexstr+2);
else
printf ("%s\n", hexstr);
return 0;
}
打印十六进制值(%x
)和地址(%p
)时,格式略有不同。在十六进制值的情况下,打印值不以0x
开头:
int main()
{
int x = 0x1234;
printf("Value of x: %x\n", x);
printf("Address of x: %p\n", (void*)&x);
}
产量(gcc):
Value of x: 1234
Address of x: 0xffb0fbfc
为什么在地址的情况下 0x
强加给你?
我想这归结为标准。
如果我愿意,在没有 0x
的情况下打印地址的正确方法是什么? %p
不只是 %x
加上 0x
对吧?
p
The argument shall be a pointer to void. The value of the pointer is converted to a sequence of printable characters, in an implementation-defined manner.
%p
的输出格式是特定于实现的。并非每个 C 实现都在地址大小与 int
相同的机器上。 intptr_t
来自 <stdint.h>
The %p is not only a %x with an added 0x right?
否.. %p
期望参数为 (void *) 类型并打印出地址。
而 %x
将无符号整数转换为无符号十六进制并打印出结果。
%p
所做的是实现定义,但标准只是说 %p
期望 void*
参数,否则行为未定义。
MSVC 不会强制我使用“0x”前缀,但您可以选择像这样删除它:
#include <stdio.h>
#include <string.h>
int main(void) {
int x = 123;
char hexstr[20];
sprintf(hexstr,"%p", (void*)&x);
if (strstr(hexstr,"0x") == hexstr)
printf ("%s\n", hexstr+2);
else
printf ("%s\n", hexstr);
return 0;
}