交换指针变量x和y所指向的存储位置处存放的值,不再使用临时存储变量。直接使用位异或运算。公式:a^a=0。对任一位向量a,有a^a=0.与通常交换两个数值的 计数不一样,当移动一个值时,我们不需要第三个位置来临时存储另一个值。
(异或加密,原理相同)
- #include <stdio.h>
- #include <time.h>
- #include<string.h>
- void inplace_swap_int(int *x,int *y){//等价于inplace_normal_int函数
- *y=*x^*y;
- *x=*x^*y;
- *y=*x^*y;
- }
- void inplace_swap_char(char *x,char *y){//等价于inplace_normal_char函数
- *y=*x^*y;
- *x=*x^*y;
- *y=*x^*y;
- }
- void inplace_normal_int(int *x,int *y){
- int temp;
- temp=*x;
- *x=*y;
- *y=temp;
- }
- void inplace_normal_char(char *x,char *y){
- char temp;
- temp=*x;
- *x=*y;
- *y=temp;
- }
- /*
- void main(){
- long start,end,timeout;
- char a='a',b='b';
- char *x=&a;
- char *y=&b;
- start=clock();
- inplace_normal_char(x,y);
- end=clock();
- timeout=start-end;
- printf("x is %c,y is %c\ntimeout is %ld\n",*x,*y,timeout);
- }
- */
- //反序整型数组
- /*
- void reverse_array(int a[],int cnt){
- int first,last;
- for(first=0,last=cnt-1;first<last;first++,last--){
- inplace_swap_int(&a[first],&a[last]);
- }
- }
- void main(){
- int a[]={1,2,3,4,5};
- int i=0;
- reverse_array(a,sizeof(a)/sizeof(int));
- for(i=0;i<sizeof(a)/sizeof(int);i++){
- printf("array a is %d\n",a[i]);
- }
- }
- */
- //反序字符数组或叫字符串
- void reverse_char_array(char a[],int cnt){
- int first,last;
- for(first=0,last=cnt-1;first<last;first++,last--){
- inplace_swap_char(&a[first],&a[last]);
- }
- }
- void main(){
- char a[]="abcdefghij";
- int i=0;
- printf("old array a is :%s\n",a);
- reverse_char_array(a,strlen(a));
- printf("new array a is :%s\n",a);
- }