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

后端 未结 4 1788
南笙
南笙 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条回答
  •  旧时难觅i
    2020-12-04 01:36

    Changes made by called function does not get reflected by the caller because you are overriding the pointer address in the called function i.e ptr = &y;.

    Initially, you passed the address of x but you are changing it with the address of y.

    If you really want to implement the concept of call by address then change value instead of address.

    Example:

    void change_by_add(int *ptr) {
        *ptr = y;  //changing value
        printf("\nInside change_by_add\t %d",*ptr);
    }
    
    void main(){
        int *p;
        p = &x;
        change_by_add(p);
        printf("\nInside main\t %d \n", *p);
        return 0;
    }
    

    Output

    Inside change_by_add     20
    Inside main  20
    

提交回复
热议问题