Search code examples
cfunctionpointerspass-by-reference

Why does the variable, passed as an address to a function, not change its value even if the value is changed in the function?


So, I passed the address of a variable to a particular function. And I changed the value of the variable using pointers inside the function, the change is reflected when I print the variable in the function. But when I print it in the main() block after calling the function, it doesn't reflect the same value.

#include<stdio.h>
int main()
{
  int result_count;
  int* result = waiter(n, number, q, &result_count);
  printf("%d",result_count);  //prints 0
}
int* waiter(int number_count, int* number, int q, int* result_count) 
{
  int t=10;
  result_count=&t;
  printf("\n%d",*result_count); //prints 10
}

So this is the code, and I tried assigning the value of "t" to "result_count", but in the main block, the value prints as 0 or just a random number.


Solution

  • Because the parameter result_count is local variable of function waiter(). Any change in it's value will reflect within waiter() function body.
    If you want to change the value of the variable whose address result_count variable is holding, then de-reference it and assign the value:

    *result_count = t;
    

    De-referencing result_count mean your program is accessing the memory of variable whose address result_count pointer variable is holding.


    For better understanding:

    Initially when waiter() function called, pointer result_count pointing to memory of argument passed to waiter():

    waiter()                  main()
    result_count              result_count (assume it's address is 100) 
            +-----+             +-----+
            | 100 |------------>|     |
            +-----+             +-----+
    
     
    

    After this statement - result_count=&t;

    waiter()                  main()
    result_count              result_count (assume it's address is 100) 
            +-----+             +-----+
            | 200 |----+        |     |
            +-----+    |        +-----+
                       |
                       |        waiter()
                       |        t       (assume it's address is 200) 
                       |        +-----+
                       +------->|     |
                                +-----+
    

    Instead, when you do - *result_count = t;

    waiter()                  main()
    result_count              result_count (assume it's address is 100) 
            +-----+             +-----+
            | 100 |------------>|  10 |
            +-----+             +-----+
    

    Hence, after returning from waiter(), when your program print result_count, it print the value assigned in the waiter() function.