867 views
0 votes
0 votes
void fun(int *p)
{
  int q = 10;
  p = &q;
  printf("%d",p);//prints 1948738932
  printf("\n");
  printf("%d q= ",&q);//prints 1948738932
  printf("\n");
  printf(" value of p  %d" ,*p);//rints 10
  printf("\n");
}

int main()
{
  int r = 20;
  int *p = &r;
  printf("%d r= ",&r);//output = 1948738964
  printf("\n");
  printf("%d",p);//output = 1948738964
  printf(" value of p  %d" ,*p);// prints 20
  printf("\n");
  fun(p);
  printf("%d", *p);//prints 20
  return 0;
}


Can anyone explain why is it giving 20 in line 2 because in function fun, address of p has been changed to point to q,so it should print value at q i.e 10??

In line 3,what is passed in the function?is it the address of p or something else?

2 Answers

3 votes
3 votes

Assume address of r = 1000

So, in the main function is p is holding the value = 1000

Now you called fun(p);

What, happens here ?

New stack frame is allocated for funciton fun().

Argument of fun() is int *p so a new pointer variable named p is also created in this stack frame and p is initialized to 1000 because of parameter passing. So far so good ! :)

Now, again another local varibale is q is allocated and initialized to 10. Assume its adress is 2000.

Then, inside fun() value of local pointer varibale p is changed to 2000.

Keep in mind that p in the stack frame of fun() is different from p in the main function. In the main funciton p is pointing to 1000.

after that you have done some printing stuff inside the fun().

Did you change pointer p in the main function ? NO

Did you change the value contained in the address 1000 ? NO.

So, why should the *p or r value change in the main function ? No change.

0 votes
0 votes
in  fun(p){p is holding the local address of q so prints 10}

on returning to main p still holds the address of r so prints 20

Related questions

3 votes
3 votes
1 answer
1
Storm_907 asked Apr 16, 2023
473 views
Please explain this question void main() { int a =300; char *ptr = (char*) &a ; ptr++; *ptr=2; printf("%d" , a); }
4 votes
4 votes
4 answers
3
Manoj Kumar Pandey asked May 22, 2019
833 views
https://gateoverflow.in/?qa=blob&qa_blobid=14433986388826671915int main() { int a = 10; int *b = &a; scanf("%d",b); printf("%d",a+50); }What will be the Output of the fol...