Click here to Skip to main content
15,911,030 members
Please Sign up or sign in to vote.
1.00/5 (3 votes)
See more:
here p is a pointer pointing to i.but how it is able to accept the value through scanf if accepted it should hold the value of given data. but it is holding the address of i. when printing the *p and i. we get the run time input as output.
Int I=5, *p;
p=&I; scanf("%d", p);
printf("%d %d\n", I, *p);


What I have tried:

yes, I have tried to predict the output but I executed the code and it is working and Im getting the results as run time input.
Posted
Updated 28-Aug-17 9:59am
v2
Comments
jeron1 28-Aug-17 15:40pm    
So is your question why are you getting the same two numbers printed?

1 solution

p is a pointer to I and scanf needs a pointer n order to know where to put the value it reads.
This is normal, because in C everything is passed t a function by value not by reference - which means that the function gets a copy of the variable rather than the variable itself. That makes a lot of sense if you thin about it:
void foo(int x)
   {
   x = x +1;
   printf("%d\n");
   }
Is fine, but what would happen if you called it like this:
foo(666);
If you didn't take a copy of the value, you would have the code trying to change the value of a constant number!

So if you want to change something in the calling function from the called function, you have to pass a pointer rather than the value, so a copy of the pointer is passes which points at the same place as the original.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month


CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900