c语言中swap问题小结

来源:互联网 发布:vm虚拟机 for mac 编辑:程序博客网 时间:2024/05/21 10:34
swap:实现交换的话,得传地址过去进行交换
    #include<stdlib.h>
    #include<stdio.h>
    void swap1(int x,int y)
    {
    int temp;
    temp=x;
    x=y;
    y=temp;
    }
    void swap2(int *x,int *y)
    {
    int *temp;
    temp=x;
    x=y;
    y=temp;
    }
    void swap3(int *x,int *y)
    {
    int temp;
    temp=*x;
    *x=*y;
    *y=temp;
    }
    void swap4(int a[],int b[])
    {
    int temp;
    temp=a[0];
    a[0]=b[0];
    b[0]=temp;
    }
    void swap5(int a[],int b[])
    {
    int temp;
    temp=*a;
    *a=*b;
    *b=temp;
    }
    int main()
    {
    int x,y;
    x=4;
    y=3;
    swap1(x,y);
    printf("swap1: x:%d,y:%d\n",x,y);//形参传值,不能交换,实际传过去是拷贝的一份,没改变主函数中x,y
    swap2(&x,&y);
    printf("swap2: x:%d,y:%d\n",x,y);//不能交换,函数中只是地址交换了下,地址指向的内容没有交换
    swap3(&x,&y);
    printf("swap3: x:%d,y:%d\n",x,y);//能交换,地址指向的内容进行了交换
    swap4(&x,&y);
    printf("swap4: x:%d,y:%d\n",x,y);//能交换,地址指向的内容进行交换
    swap5(&x,&y);
    printf("swap5: x:%d,y:%d\n",x,y);//能交换,地址指向的内容进行交换
    return 0;
    }
    swap1: x:4,y:3
    swap2: x:4,y:3
    swap3: x:3,y:4
    swap4: x:4,y:3
    swap5: x:3,y:4