what actually happen when C programmer write scanf("%d",i) instead of scanf("%d",&i)?
-by Ayush garg
Prerequisite
for batter understanding-
Some time
programmer made a mistake and instead writing following code
//Program 1
void main()
{
int I;
scanf(“%d”,&i);
printf(“The value of i=%d”,i);
}
Programmer write
//program 2
void main()
{
int I;
scanf(“%d”,i);
printf(“The value of i=%d”,i);
}
Program 2
sometime run sometime not. If program 2
run it display undefined or unexpected output.
As we know
in scanf() call by reference is used and when program run some memory allocate
to the variable i at some address inside a RAM. That address is pass to
function scanf(). scanf contain pointer variable as an argument. But In program 2 instead to passing address we
are passing the value inside the variable i. And that value is received by the
pointer variable of scanf() .
Initially i contain garbage. That garbage
value is passed to pointer variable and
pointer variable start point to that location. If garbage is to large then
the size of the memory cause program is crash (means not run) . If the size of
the garbage is smaller than size of the memory then display the garbage value.
In that case program take input but that
input is store at place where pointer is pointing . And display the value at i
and initially garbage is stored at i.
Thank you.
If you have any suggestion for improvement or found mistake or if you like please writer in comment in the comment section and share it.
Comments
Post a Comment