开发者

difference between printing a memory address using %u and %d in 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 auth开发者_如何学JAVAor wrote:

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

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

Can anyone elaborate on this, please?

Thanks a lot.


%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.

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.

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.

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.

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"

The exact output format is implementation-defined (C99 §7.19.6.1/8), but it will almost always be printed as an unsigned hexadecimal number, usually with a leading 0x.


%d and %u will print the same results when the most significant bit is not set. However, this isn't portable code at all, and is not good style. I hope your book is better than it seems from this example.


What value did you try? The difference unsigned vs. signed, just as you said you know. So what did it do and what did you expect?

Positive signed values look the same as unsigned so can I assume you used a smaller value to test? What about a negative value?

Finally, if you are trying to print the variable's address (as it appears you are), use %p instead.


All addresses are unsigned 32-bit or 64-bit depending on machine (can't write to a negative address). The use of %d isn't appropriate, but will usually work. It is recommended to use %u or %ul.


There is no such difference ,just don't get confused if u have just started learning pointers. %u is for unsigned ones.And %d for signed ones

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜