Reputation: 18109
When printing a hexadecimal value (%x
) and an address (%p
), the format is slightly different. The printed value does not start with 0x
in the case of a hexadecimal value:
int main()
{
int x = 0x1234;
printf("Value of x: %x\n", x);
printf("Address of x: %p\n", (void*)&x);
}
yields (gcc):
Value of x: 1234
Address of x: 0xffb0fbfc
Why is the 0x
forced on you in the case of an address?
I guess it boils down to the standard.
What would be the correct way to print an address without the 0x
if i wanted to? The %p
is not only a %x
with an added 0x
right?
Upvotes: 7
Views: 11421
Reputation: 19864
The %p is not only a %x with an added 0x right?
No.. %p
expects the argument to be of type (void *) and prints out the address.
Whereas %x
converts an unsigned int to unsigned hexadecimal and prints out the result.
And coming to what %p
does is implementation defined but the standard just says that %p
expects void*
argument else the behavior is undefined.
Upvotes: 3
Reputation: 34585
MSVC does not force the "0x" prefix on me, but you could optionally remove it like this:
#include <stdio.h>
#include <string.h>
int main(void) {
int x = 123;
char hexstr[20];
sprintf(hexstr,"%p", (void*)&x);
if (strstr(hexstr,"0x") == hexstr)
printf ("%s\n", hexstr+2);
else
printf ("%s\n", hexstr);
return 0;
}
Upvotes: 1
Reputation: 1
The output format for %p
is implementation specific. Not every C implementation is on machines with addresses of the same size as int
. There is the intptr_t
from <stdint.h>
Upvotes: 5