in Programming in C edited by
1,568 views
4 votes
4 votes
void fun(int *p)
{
    int q = 10;
    p = &q; z
}    
int main()
{
    int r = 20;
    int *p = &r;
    fun(p);
    printf("%d", *p);
    return 0;
}
in Programming in C edited by
1.6k views

1 comment

p is passed by value. So, original p remains intact, and keeps pointing to r.
0
0

4 Answers

3 votes
3 votes
Best answer
Ignoring the mysterious "z" in body of fun,

Output: 20

when we call fun from main, the address of r(say 1000) which is stored in p is copied to "p" in fun,

In fun, we are not changing the value at this address 1000, what we're doing in line p=&q is changing the address itself, i.e now p of fun holds another address(say 2000). so back in main, there are no changes, the p of main still holds the address 1000, which has value 20

Now to be more clear about when value changes and when it doesn't, try this: copy-paste this code and add line *p=30(or any random int value you can think of) in fun before p=&q line once, then move it below p=&q, observe the changes in output.
selected by

4 Comments

is it due to scope of variable?... since it is a call by reference hence actually address of r is being sent to fun p. and there p starts to point q.. since original p was sent then in main *p should print 10?
0
0
Address of r i.e 1000(say), is copied in main - P, then it is copied in fun-P, then fun-P (which is just a variable to hold an int address) changes it value to address of q(say 3000), now main-P is still pointing to 1000, if we had changed value at address 1000 then we might be seeing any change in O/P
0
0
It's the best answer with the best explanation.
0
0
1 vote
1 vote

Output: 20

It is an example of call by reference method.

In which we pass an address of a variable in the function as a parameter and whatever values are manipulated within the function they don't have any impact on original values.

here, we pass the address of integer r and store it in the p (pointer to the integer) then passed the p in the function fun and then p values are manipulated in the function but as it is a call by reference (we just send the reference not the actual value of p)

when printf statement executes the value of p is taken from the main function.

Therefore the output is 20

1 vote
1 vote
The output will be 20

Because in C,the scope of ay local variable or function parameter is only within that function,

Thus here,the vaue of *p will become 10 but only till it is in the function body,as soon as it comes back to the main(),the value of *p becomes 20
1 vote
1 vote
Here p in fun is is formal parameter so it's life time is lime time of the function one the function fun gets executed the value assigned to the formal parameter is lost. So, in the main function the value of *p (which is actually different to that of the corresponding formal parameter) remains 20. so, 20 is printed

Related questions