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

后端 未结 4 1776
南笙
南笙 2020-12-04 00:40

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 functi

4条回答
  •  既然无缘
    2020-12-04 01:32

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

提交回复
热议问题