0
#include<stdio.h>

int q = 10;

void fun(int *p){
    *p = 15;
    p = &q;
    printf("%d ",*p);
}    

int main(){
  int r = 20;
  int *p = &r;  
  fun(p);
  printf("%d", *p);
  return 0;
}

I was playing with pointers. Could not understand the output of this. Output is coming as 10 15. Once p is pointing to address of q, why on returning to main function it's value changes? Also why it changed to the value '15' which was assigned to it in the function before '10'.

3 Answers 3

5

Because p is fun() is not the same p in main(). p , in each function, is local. So changing one doesn't affect other.

Sign up to request clarification or add additional context in comments.

2 Comments

But it is showing output as 15 inside main! It should be 20 then
Because you are chaning the value point to by p in fun() with: *p = 15; Note that there is a difference in changing the value of pointer and what it's point to.
4

In C, all function parameters are passed by value, including pointers.

*p = 15; will set r to 15 as *p is pointing to the memory occupied by r in main() prior to its reassignment to &q;

Your reassignment p = &q; does not change what p points to in the caller main(). To do that, you'd need to doubly indirect the pointer, i.e. change the function prototype to void fun(int **p){, call it using fun(&p);, and reassign using *p = &q;.

1 Comment

Then how come it is showing 15 as output inside main function?
1

Two steps:

  1. First call to fun(), assigning the address of global int q [holding value 10] to p inside the fucntion scope and printing it. The first output ==> 10;

  2. Once the call returns from fun(), it will hold the previous address, [passed from main()] and hence, will print the value held by that address [which is 15, modified inside fun()].

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.