views:

157

answers:

2

What is difference between %d and %u when printing pointer addresses?

For example:

int a=5;
// check the memory address
printf("memory add=%d\n", &a); // prints "memory add=-12"
printf("memory add=%u\n", &a); // prints "memory add=65456"

Please define.

+9  A: 

You can find a list of formatting escapes on this page.

%d is a signed integer, while %u is an unsigned integer. Pointers (when treated as numbers) are usually non-negative.

If you actually want to display a pointer, use the %p format specifier.

GMan
Interesting that his example shows a negative value, then! It depends on the machine, but I'd say addresses with a leading one-bit are fairly common on 32-bit machines, but less so on 64-bit machines.
Jonathan Leffler
Please explain the down vote.
GMan
Yeah right, GMan. Why would somebody say "this answer is bad" but then give advice to improve it? That would be productive.
GMan
+4  A: 

If I understand your question correctly, you need %p to show the address that a pointer is using, for example:

int main() {
    int a = 5;
    int *p = &a;
    printf("%d, %u, %p", p, p, p);

    return 0;
}

will output something like:

-1083791044, 3211176252, 0xbf66a93c
Luca Matteis