格式说明符:%u vs%d在C中
#include<stdio.h>
int main(){
int a = 3;
printf("%u\n",&a);
printf("%d\n",&a);
return 0;
}
我试图打印变量的地址,“ a”。现在,使用两个不同格式指定符“%u”和“%d”,打印了两个不同的内存地址,我觉得这是Wierd的。
所以我的问题是两种格式指定符之间有什么区别?
#include<stdio.h>
int main(){
int a = 3;
printf("%u\n",&a);
printf("%d\n",&a);
return 0;
}
I was trying to print address of Variable, "a". Now with usage of two different format specifier, "%u" and "%d", two different memory address is printed which I find it wierd.
So My Question is what difference between two format specifier?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
使用两个转换说明器输出地址都调用不确定的行为。
从C标准(7.21.6.1 FPRINTF函数)
相反,您应该使用转换规范<代码> p ,例如
另一种方法是使用整数类型
intptr_t
或uintptr_t
在标题&lt; stdint.h&gt;
中声明并使用说明器pridptr
或priuptr
或例如prixptr
在标题中声明&lt; inttypes.h&gt;
to type的指数的输出值分配的值
void *
。这是一个演示程序。
程序输出是
Using the both conversion specifiers to output an address invokes undefined behavior.
From the C Standard (7.21.6.1 The fprintf function)
Instead you should use the conversion specifier
p
as for exampleAnother approach is to use integer types
intptr_t
oruintptr_t
declared in the header<stdint.h>
and to use specifiersPRIdPTR
orPRIuPTR
or, for example,PRIxPTR
declared in the header<inttypes.h>
to output assigned values of pointers of the typevoid *
.Here is a demonstration program.
The program output is
%d
用于签名整数,%u
用于无符号整数。因此,当您使用
%d
和%u
打印出相同的值时,您可能会得到不同的值,因为您要打印的字节的解释方式有所不同。 (一旦作为签名的整数,一次是无符号整数。)最终说明,您应该使用
%p
(“ p”作为“指针”)来打印地址。%d
is for signed integers,%u
is for unsigned integers.So, when you print the same value out with
%d
and with%u
, you may get different values, since the bytes you're printing out are being interpreted differently. (Once as a signed integer, once as an unsigned integer.)Final note, you should use
%p
("p" for "pointer") to print out addresses.当然,
“%u \ n”
的地址不同于“%d \ n”
,因为这些是一个接一个地创建的不同值。查看ASM:rdx
寄存器都有相同的值printf
呼叫由于LEA指令,将相同的地址放入其中。但是您可能看到的是
rcx
寄存器的值,其中包含不同的printf
格式值地址printf
呼叫。现在答案:
%d
已签署了十进制整数。%u
是未签名的十进制整数。当有一个
printf
调用时,就会发生问题。此功能更改RDX寄存器的值,RDX寄存器是a
变量的内存地址。Well of course
"%u\n"
has different address than"%d\n"
because these are different values created one after another. Look at ASM:RDX
register will have the same value for bothprintf
calls because of LEA instruction is putting the same address into it.But what you probably see are the values of
RCX
register which contains differentprintf
format value address for eachprintf
call.Now the answer:
%d
is signed decimal integer.%u
is unsigned decimal integer.The problem occurs when there is a
printf
call. This function changes the value of RDX register which is the memory address ofa
variable.