c语言中swap问题小结

2014-11-24 00:40:13 · 作者: · 浏览: 57

#include
#include

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

摘自 无聊中的博客