c语言交换两个字符:

方法一:利用指针传址,效率比较高

1 void swap(int *a,int *b)
2 {
3     int temp;
4     temp = *a;
5     *a = *b;
6     *b = temp  
7 }

方法二:利用引用加减或乘除运算来交换,存在缺陷,有可能导致溢出

swap(int &a,int &b)
{
   a = a+b;//a=a*b;
   b = a-b;//b=a/b;
   a = a-b; //a=a/b;
}

方法三:引用异或

1 void swap(int &a,int &b)
2 {
3    a ^= b;
4    b ^= a;
5    a ^ =b;    
6 }    

c语言交换两个字符串:利用指针改变地址

1 void  swap(char **a,char **bb)
2 {
3    char *temp;
4    *temp  = *a;
5    *a = *b;
6    *b = *temp;  
7 }

 

Copyright © 2024 冬阳阳
Powered by .NET 9.0 on Kubernetes