Home > Net >  Why I am not receiving a hexadecimal number as output when I print a pointer address with %p?
Why I am not receiving a hexadecimal number as output when I print a pointer address with %p?

Time:01-21

I have written a program while learning pointers in c and facing a problem. My code was to print the address of the variable which should be a hexadecimal number. But why I am receiving an integer number instead of a hexadecimal number. Please help me out to print the hexadecimal number starting with "0x" . Thank you.

Note that my IDE was Visual Studio Code and the compiler I am using is GCC.

#include <stdio.h>

int main(void)
{
    char *a = "abcd";
    for (int i = 0; i<4; i  )
    {
        printf("%p\n",&a[i]);
    }
    
}

Output :

00405064
00405065
00405066
00405067

I was expecting a number starting with "0x"

CodePudding user response:

It's not defined what %p uses as a format to print the address.

However, it's common for it to be displayed in hexadecimal.

So, if you want to print the hexadecimal number of a pointer the most portable way I know of (C99 & above) is:

#include <stdio.h>
#include <inttypes.h> // PRIxPTR

int main(void) {
    const char *a = "abcd"; // 'const' because a is not modifiable

    for (int i = 0; i<4; i  ) {
        uintptr_t tmp = (uintptr_t)&a[i];

        printf("0x%" PRIxPTR "\n", tmp);
    }
}

CodePudding user response:

Everything seems just fine in your code sample. I tested it on three different online compilers and produced expected output:

Output on compiler 1:

0x55cf7d06c004
0x55cf7d06c005
0x55cf7d06c006
0x55cf7d06c007

Output on compiler 2:

0x55dfc15c0004
0x55dfc15c0005
0x55dfc15c0006
0x55dfc15c0007

Output on compiler 3:

0x4005c0
0x4005c1
0x4005c2
0x4005c3

So, I guess is something in your IDE/compiler.

  • Related