在用^交换a,b值时操作地址和操作值的区别

来源:互联网 发布:知美术馆官网 电话 编辑:程序博客网 时间:2024/06/13 08:14
// PracticeProblem2.10.cpp : 定义控制台应用程序的入口点。
//


#include "stdafx.h"
#include "stdio.h"
void inplace_swap(int* x, int* y)
{
*y = *x ^ *y;
*x = *x ^ *y;
*y = *x ^ *y;
}


void reverse_array(int a[], int cnt)
{
int first, last;
for(first = 0, last = cnt -1; first <= last; first ++, last --)
{


inplace_swap(&a[first], &a[last]);
}
}


int _tmain(int argc, _TCHAR* argv[])
{
int a[9] = {1, 2, 3, 4, 5, 6, 7, 8, 9};
reverse_array(a, 9);
for (int i = 0; i < 9; i++)
{
printf("a[%d]=%d\n", i, a[i]);

}


int c = 5;
int b = 5;
inplace_swap(&b, &c);
printf("b: %d, c: %d", b, c);
getchar();


return 0;

}

运行结果:

a[0] = 9

a[1] = 8

a[2] = 7

a[3] = 6

a[4] = 0

a[5] = 4

a[6] = 3

a[7] = 2

a[8] = 1

b = 5, c = 5


我们知道:b = a ^ b;
           a = a ^ b;
           b = a ^ b;可以交换a, b的值,那么为什么在上面的测试程序中,b,c是相同的值,交换值成功,而在数组中,a[4]的值却直接变成0了呢?

这是因为,在交换b,c的值的时候,我们操作的是不同的地址 ,当c = b^c= 0的时候,只改变了c的值,却没有改变b的值,所以,当再次c=c^b的时候 ,c可以交换成b的值;

可是在传递数组a[4]给inplace_swap函数时,是传递的两个相同的地址&a[4]给此函数,所以,a[4]=a[4]^a[4] = 0,这个地址中存的内容永远为0了,下面的交换计算永远是0^0,再也不能还原回来了。 

原创粉丝点击