Search code examples
cprintfformat-string

Why is the format of %p and %x different in a format string?


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?


Solution

  • p

    The argument shall be a pointer to void. The value of the pointer is converted to a sequence of printable characters, in an implementation-defined manner.

    reference