difference between printing a memory address using %u and %d in C?

ipkiss picture ipkiss · Mar 6, 2011 · Viewed 58.5k times · Source

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);

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.

Answer

Adam Rosenfield picture Adam Rosenfield · Mar 6, 2011

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