Home > Back-end >  Why I am receiving a hexadecimal number as an output from my c program?
Why I am receiving a hexadecimal number as an output from my c program?

Time:01-06

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:

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.

CodePudding user response:

The number you're seeing is in hexadecimal.

See:

   p      The void * pointer argument is printed in hexadecimal (as
          if by %#x or %#lx).

It's not required to be prefixed with 0x although that helps with clarity.

By the way, since you're using %p you need to cast your pointer to void * like so:

printf("%p\n", (void *)&a[i]);
  • Related