c语言中swap问题小结_c语言中swap
c语言中swap问题小结由刀豆文库小编整理,希望给你工作、学习、生活带来方便,猜你可能喜欢“c语言中swap”。
#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:%dn”,x,y);//形参传值,不能交换,实际传过去是拷贝的一份,没改变主函数中x,y swap2(&x,&y);
printf(“swap2: x:%d,y:%dn”,x,y);//不能交换,函数中只是地址交换了下,地址指向的内容没有交换 swap3(&x,&y);
printf(“swap3: x:%d,y:%dn”,x,y);//能交换,地址指向的内容进行了交换 swap4(&x,&y);
printf(“swap4: x:%d,y:%dn”,x,y);//能交换,地址指向的内容进行交换 swap5(&x,&y);
printf(“swap5: x:%d,y:%dn”,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