What is difference between %d
and %u
when printing pointer addresses?
For example:
int a = 5;
// check the memory address
printf("memory address = %d\n", &a); // prints "memory address = -12"
printf("memory address = %u\n", &a); // prints "memory address = 65456"
This question is related to
c
pointers
formatting
printf
%u is used for unsigned integer. Since the memory address given by the signed integer address operator %d is -12, to get this value in unsigned integer, Compiler returns the unsigned integer value for this address.
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.
%u prints unsigned integer
%d prints signed integer
to get a pointer address use %p
Here are the full list of formatting escapes. I am just giving a screen shot from this page
The difference is simple: they cause different warning messages to be emitted when compiling:
1156942.c:7:31: warning: format ‘%d’ expects argument of type ‘int’, but argument 2 has type ‘int *’ [-Wformat=]
printf("memory address = %d\n", &a); // prints "memory add=-12"
^
1156942.c:8:31: warning: format ‘%u’ expects argument of type ‘unsigned int’, but argument 2 has type ‘int *’ [-Wformat=]
printf("memory address = %u\n", &a); // prints "memory add=65456"
^
If you pass your pointer as a void*
and use %p
as the conversion specifier, then you get no error message:
#include <stdio.h>
int main()
{
int a = 5;
// check the memory address
printf("memory address = %d\n", &a); /* wrong */
printf("memory address = %u\n", &a); /* wrong */
printf("memory address = %p\n", (void*)&a); /* right */
}
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
Source: Stackoverflow.com