c语言中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

posted on 2012-04-08 14:15 一叶草 阅读(1870) 评论(0)  编辑 收藏 引用

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理