2011-08-10 18 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++; 
} 
相關問題