MrTambourineMan
MrTambourineMan

Reputation: 1045

Pointers inside function in C

#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'.

Upvotes: 0

Views: 1119

Answers (3)

Sourav Ghosh
Sourav Ghosh

Reputation: 134396

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()].

Upvotes: 1

Bathsheba
Bathsheba

Reputation: 234875

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;.

Upvotes: 4

P.P
P.P

Reputation: 121427

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

Upvotes: 5

Related Questions