打印使用%u和%d个在C内存地址之间的区别? [英] difference between printing a memory address using %u and %d in C?

查看:1161
本文介绍了打印使用%u和%d个在C内存地址之间的区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我读一本C语言书中。要打印出一个变量的内存地址,有时本书使用:

I reading a C book. To print out a memory address of a variable, sometimes the book uses:

printf("%u\n",&n);

有时,作者写道:

Sometimes, the author wrote:

printf("%d\n",&n);

结果总是相同的,但我不明白之间的差别两个(我知道%U不带符号)。

The result is always the same, but I do not understand the differences between the two (I know %u for unsigned).

有人能解释一下吗?

非常感谢。

推荐答案

%U 对待整数为无符号,而%d个对待整数作为签名。如果整数为0之间的 INT_MAX (这是2 31 -1在32位系统),则输出是两种情况下相同

%u treats the integer as unsigned, whereas %d treats the integer as signed. If the integer is between 0 an INT_MAX (which is 231-1 on 32-bit systems), then the output is identical for both cases.

这不仅使一个区别,如果该整数为负(有符号输入)或 INT_MAX + 1 UINT_MAX (例如,在2 31 2 32 -1)。在这种情况下,如果你使用%d个符,你会得到一个负数,而如果你使用%U ,你会得到一个大的正数。

It only makes a difference if the integer is negative (for signed inputs) or between INT_MAX+1 and UINT_MAX (e.g. between 231 and 232-1). In that case, if you use the %d specifier, you'll get a negative number, whereas if you use %u, you'll get a large positive number.

地址才有意义为无符号数,因此从来任何理由打印出来作为符号数。此外,当它们被打印出来,他们通常以十六进制(与%X 格式说明),不是小数。

Addresses only make sense as unsigned numbers, so there's never any reason to print them out as signed numbers. Furthermore, when they are printed out, they're usually printed in hexadecimal (with the %x format specifier), not decimal.

您真的应该只使用%P 格式说明了地址,虽然,它是保证所有有效的指针工作。如果你的系统上的32位整数,但64位指针,如果您尝试打印一个指针与任何%d个的%U %X 没有 LL 长度修改,你会得到对于和其他任何后来被印错的结果(因为的printf 只能读取8个字节的指针参数为4);如果你添加 LL 长度修改,那么你将无法移植到32位系统。

You should really just use the %p format specifier for addresses, though—it's guaranteed to work for all valid pointers. If you're on a system with 32-bit integers but 64-bit pointers, if you attempt to print a pointer with any of %d, %u, or %x without the ll length modifier, you'll get the wrong result for that and anything else that gets printed later (because printf only read 4 of the 8 bytes of the pointer argument); if you do add the ll length modifier, then you won't be portable to 32-bit systems.

底线:总是用%P 打印出指针/地址:

Bottom line: always use %p for printing out pointers/addresses:

printf("The address of n is: %p\n", &n);
// Output (32-bit system): "The address of n is: 0xbffff9ec"
// Output (64-bit system): "The address of n is: 0x7fff5fbff96c"

确切的输出格式为实现定义(C99§7.19.6.1/ 8),但它几乎总是被打印为无符号十六进制数,通常有一个领先的 0X

这篇关于打印使用%u和%d个在C内存地址之间的区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆