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

4

7

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?

Telemachus answered 25/2, 2015 at 10:10 Comment(2)
you might take a look at https://mcmap.net/q/1476074/-printf-ptr-can-the-leading-0x-be-eliminatedGloriagloriana
Note that you should be passing an unsigned int to printf for %x, for instance by declaring x of this type.Martyrize
O
11

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

Obreption answered 25/2, 2015 at 10:13 Comment(0)
I
5

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>

Industrialist answered 25/2, 2015 at 10:13 Comment(0)
B
3

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.

Bowman answered 25/2, 2015 at 10:18 Comment(0)
H
1

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;
}
Hyonhyoscine answered 25/2, 2015 at 10:32 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.