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("%pn",&a[i]);
}
}
Output :
00405064
00405065
00405066
00405067
I was expecting a number starting with "0x"
2
Answers
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:
Everything seems just fine in your code sample. I tested it on three different online compilers and produced expected output:
Output on compiler 1:
Output on compiler 2:
Output on compiler 3:
So, I guess is something in your IDE/compiler.