#include<stdio.h>
void main()
{
int i = 5;
printf("%p",i);
}
I tried to compile this program on Linux using GCC compiler which on compilation of the program issues a warning saying
%p expects a void* pointer
and when run gives an output of 46600x3.
But when I compile it online using the site codingground.tutorialspoint.com I get an output
equals 0x5 i.e. a hexadecimal output, can anyone please explain the reason?
%p expects the address of something(or a pointer). You provide the value of the variable i instead of the address. Use
printf("%p",(void*)&i);
instead of
printf("%p",i);
and GCC will compile the program without warnings and it will print the address where i is stored when you run it. The ampersand(&) is the address-of operator and it gives the address of the variable. The cast is also neccessary as the format specifier %p expects an argument of type void* whereas &i is of type int*.
printf("%d",i);
Using the wrong format specifier will lead to UB(Undefined Behavior)
printf("%p",i);
Using wrong format specifier will lead to undefined behavior. %p expects the arguement of type void * in your case you are passing the value of i and not the address in order to print out the address you should pass &i
You should use
printf("%d",i);
to print the integer value of i
The code should be like
#include<stdio.h>
void main()
{
int i = 5;
printf("%d",i); /* To print value of i */
printf("%p",(void *)&i); /* Address of variable i */
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With