edited by
1,522 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;
}
edited by

4 Answers

Best answer
3 votes
3 votes
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
1 votes
1 votes

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 votes
1 votes
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 votes
1 votes
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

5 votes
5 votes
1 answer
1
amrendra pal asked Aug 28, 2017
492 views
#include<stdio.h int Abc(){ static int i = 19; return i; } int main(){ for(Abc() ; Abc() ; Abc()){ printf("%d ", Abc()); } return 0; }
0 votes
0 votes
1 answer
2
2 votes
2 votes
2 answers
4
atulcse asked Jan 15, 2022
662 views
Consider the following programint find (int n) { int a = 1; for (i = 1; i < = n; i ++) for (j = 1; j < = i; j++) for (k = 1; k <= j, k++) a = a + 1; ...