Unexpected output when printing integer value

#include<stdio.h> void main() { int i = 5; printf("%p",i); } 

I tried to compile this program on Linux using the GCC compiler which, when compiling the program, gives a warning

 %p expects a void* pointer 

and at startup, the output is 46600x3.

But when I compile it on the Internet using codingground.tutorialspoint.com, I get an output equal to 0x5 i.e. hexadecimal conclusion, can someone explain the reason?

+5
source share
2 answers

%p expects the address of something (or a pointer). You specify the value of the variable i instead of the address. Use

 printf("%p",(void*)&i); 

instead

 printf("%p",i); 

and GCC will compile the program without warning, and it will print the address where i saved when it starts. Ampersand ( & ) is the address of the operator and gives the address of the variable. A cast is also needed because the %p format specifier expects an argument of type void* , while &i is of type int* .


If you want the variable value to be printed, use
 printf("%d",i); 

Using the wrong format specifier will result in UB (Undefined Behavior)

+6
source
 printf("%p",i); 

Using the wrong format specifier will result in undefined behavior. %p waiting for an approval of type void * in your case you pass the value i , not the address, to print the address that you must pass &i

You have to use

 printf("%d",i); 

to print the integer value 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 */ } 
+4
source

Source: https://habr.com/ru/post/1210298/


All Articles