• C语言值传递,地址传递,引用传递


    C语言参数传递方式:
    值传递(swap1函数)
    地址传递(swap2函数)
    引用传递(swap3函数)

    #include<stdio.h>
    #include<windows.h>
    void swap1(int,int);          //值传递
    void swap2(int *p1,int *p2);  //地址传递
    void swap3(int &a,int &b);    //引用传递
    int main(void)
    {
        int x=3,y=5;
        printf("main address of a = %d,b=%d
    ",&x,&y);
        swap1(x,y);
        printf("the number of a=%d,b=%d
    ",x,y);
        swap2(&x,&y);
        printf("the number of a=%d,b=%d
    ",x,y);
        swap3(x,y);
        printf("the number of a=%d,b=%d
    ",x,y);
        system("pause");
        return 0;    
    } 
    void swap1(int a,int b)     //不影响main函数中值的变化
    {
        int temp;
        printf("swap1 address of temp = %d,a=%d,b=%d
    ",&temp,&a,&b);
        temp = a;
        a = b;
        b = temp;
    }
    void swap2(int *p1,int *p2)   //主函数中x,y的值会变化
    {
        
        int temp;
        printf("swap address of temp = %d,p1=%d,p2=%d
    ",&temp,p1,p2);
        temp = *p1;
        *p1 = *p2;
        *p2 = temp; 
    }
    void swap3(int &a,int &b)  //主函数中x,y的值会变化
    {
        int temp;
        printf("swap3 address of temp = %d,a=%d,b=%d
    ",&temp,&a,&b);
        temp = a;
        a = b;
        b = temp;
    }

    通过运行结果我们能够看到函数swap2和swap3所传递进去的地址的值和main函数中x,y地址是相同的,这也就证明了地址传递和引用传递都是直接传递的变量所在的地址,函数的主要的作用就是对存储在地址中的变量进行直接的操作,所以调用过swap2和swap3后,能够成功修改其中的值,而调用swap1函数时,程序在调用子函数时会为x y重新开辟内存,并将实参的值复制到a b中去,这也就解释了为什么swap1中a和b的地址是和main函数和swap2函数,swap3函数不同的原因!

    总结:
    1.传值调用中程序在调用子函数时会为a b重新开辟内存,并将实参的值复制到a b中去,然后在swap1函数中,a b确实发生交换了,但这跟主函数中的x y毫无关系呀,x y并未发生改变呀
    2.用了引用变量后,就不再为形参开辟内存,所有操作都是直接修改实参变量。

    参考:https://blog.csdn.net/wuzhuceji/article/details/104111160

  • 相关阅读:
    谈谈-开源数据库LitePal
    谈谈-Android-PickerView系列之封装(三)
    谈谈-Android-PickerView系列之源码解析(二)
    谈谈-Android-PickerView系列之介绍与使用(一)
    谈谈-ConstraintLayout完全解析
    问题解决-Failed to resolve: com.android.support.constraint:constraint-layout:1.0.0-alpha7
    谈谈-BaseAdapter的封装
    谈谈-使用SparseArray和ArrayMap代替HashMap
    Spring 集成Redis Cluster模式
    Redis三种集群模式-Cluster集群模式
  • 原文地址:https://www.cnblogs.com/hahahakc/p/14241166.html
Copyright © 2020-2023  润新知