cpointerscall-by-value

Passing address, but it is working like call by value in C?


Hello I am a beginner in C programming language. Recently I read about call by value and call by address. I have learned that in call by address changes in the called functions reflects the callee. However the following code does not work like that.

int x = 10,y = 20;
void change_by_add(int *ptr) {
    ptr = &y;
    printf("\n Inside change_by_add\t %d",*ptr);
    // here *ptr is printing 20
}

void main(){
    int *p;
    p = &x;
    change_by_add(p);
    printf("\nInside main\t %d", *p);
    // here *p is still pointing to address of x and printing 10
}

When I am passing address then why the changes made by called function does not reflect caller?


Solution

  • The function is assigning a new address to the pointer but the pointer itself is being passed by value, as all arguments are in C. To change the value of a pointer variable the address of the pointer itself must be passed:

    void change_by_add(int **ptr)
    {
        *ptr = &y;
    }
    
    change_by_add(&p);
    

    See C FAQ Question 4.8.

    Passing by reference does not exist in C but can be achieved by passing the address of the variable who's value is to be changed to a function. For example:

    void add_to_int(int* a_value, int a_increment)
    {
        *a_value += a_increment;
    }