Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unexpected output when printing the value of an integer

#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?

like image 678
Rupesh Narayan Avatar asked Jan 03 '15 10:01

Rupesh Narayan


2 Answers

%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*.


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

Using the wrong format specifier will lead to UB(Undefined Behavior)

like image 169
Spikatrix Avatar answered Nov 13 '22 06:11

Spikatrix


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 */
}
like image 42
Gopi Avatar answered Nov 13 '22 05:11

Gopi