Passing address, but it is working like call by va

2019-01-12 08:28发布

问题:

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?

回答1:

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


回答2:

You are simply setting the value of the pointer in the function, not the value of the pointed to variable. The function should use the following code:

*ptr = y;

This derefences the pointer (exposing the value pointed to), and therefore when you use the equals operator, the memory pointed at is modified, not the pointer itself. I hope this helps to clarify things.



回答3:

There is no such thing as call by address in C. There is only call by value. What one does when a function needs to modify an argument in a way that is visible to the caller is to have the caller pass a pointer to something, and have the called function write the update though that pointer. Note that the pointer itself is still sent as call-by-value - that is: the called function gets its own copy of the pointer and could change it to point to anything else if it wants to.