2011-08-10 20 views
0

我有两个数组说:int array1 [6] = {2,4,5,7,9}; & INT数组2 [6] = {0,5,6,7,3}在不使用临时变量的情况下在C中交换两个不同数组的元素

我将通过这些给函数交换(数组1,数组2)

目前我试图做如下

index =0; 
while(array1[index] && array2[index] != NULL) 
{ 
    array1[index] = array1[index]^array2[index]; 
    array2[index] = array1[index]^array2[index]; 
    array1[index] = array1[index]^array2[index]; 
    index++; 
} 

我的方法正确吗?请让我知道你的意见

PS:我不能发送数组长度作为参数的函数。我想用C语言来做到这一点。

感谢

+3

为什么AREN”你使用临时变量吗?老实说,我敢肯定,编译器可以优化'int array3 [6]; memcpy(array3,array1,sizeof array1); memcpy(array1,array2,sizeof array1); memcpy(array2,array3,sizeof array1);'比你的代码更快。以您找到最清晰的方式编写,然后优化,如果您发现它是性能问题。 –

+0

谢谢克里斯。使用临时会解决。但有什么办法,我们可以做到这一点,而不需要使用温度和不必传递数组长度? – Kelly

+1

使用指针可能会更方便,只需交换指针,而不是复制两个数组的全部内容。 –

回答

1

array2[index] != NULL是错误的 - 它不是一个指针在所有的,而你对一个指针值进行比较吧。 array1[index]也不是正确的测试 - 只有当数组在某个位置包含零时才可以为false,否则一旦超过分配区域就会处理未定义的行为。

您应该将数组的长度传递给该函数,然后while循环的条件应为index < length

+0

感谢Blagovest,我错过了那部分,但是有没有办法在不通过数组长度的情况下做到这一点? – Kelly

+0

@Kelly - No.在C中,您必须传递数组长度。你只能传递一个长度并告诉用户你的代码有未定义的行为来使用不同长度的数组,但是没有办法只是“知道”传递给函数的数组长度。 –

+0

@Kelly:看看这种方法:http://stackoverflow.com/questions/6966570/why-declare-a-struct-that-only-contains-an-array-in-c –

3

while条件是错误的,你可以输入较少。

for (index = 0; index < len; index++) { 
    array1[index] ^= array2[index]; 
    array2[index] ^= array1[index]; 
    array1[index] ^= array2[index]; 
} 

或者您可以使用此C FAQ所示的临时变量。

1

纠正你的,而条件,你可以使用while循环

index = len; 
while(index--) { 
    array1[index] ^= array2[index]; 
    array2[index] ^= array1[index]; 
    array1[index] ^= array2[index]; 
} 

或使用您的长度信息直接

while(len--) { 
    array1[len] ^= array2[len]; 
    array2[len] ^= array1[len]; 
    array1[len] ^= array2[len]; 
} 
1

只要改变这样的状况,

index =0; 
while(array1[index] != NULL && array2[index] != NULL) 
{ 
    array1[index] ^= array2[index]; 
    array1[index] ^= array2[index]; 
    array1[index] ^= array2[index]; 
    index++; 
} 
相关问题