[英]Swapping elements of two distinct arrays in C without using temporary variable
我有兩個數組說 int array1[6] = { 2, 4, 5, 7, 9 }; & int array2[6] = {0,5,6,7,3}
我會將這些傳遞給 function swap(array1,array2)
我目前正在嘗試按以下方式進行
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:我無法將數組長度作為參數發送到 function。 我想用 C 語言來做這件事。
謝謝
while
條件錯誤,您可以少輸入。
for (index = 0; index < len; index++) {
array1[index] ^= array2[index];
array2[index] ^= array1[index];
array1[index] ^= array2[index];
}
或者,您可以使用此C FAQ所示的臨時變量。
array2[index] != NULL
是錯誤的 - 它根本不是指針,您正在將它與指針值進行比較。 array1[index]
作為測試也不是正確的 - 如果數組在某些 position 處包含零,它只能是錯誤的,否則一旦 go 超過分配的區域,您將處理未定義的行為。
您應該將 arrays 的長度傳遞給 function ,然后while
循環的條件應該是index < length
。
更正您的while條件,您可以使用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];
}
就這樣改變條件,
index =0;
while(array1[index] != NULL && array2[index] != NULL)
{
array1[index] ^= array2[index];
array1[index] ^= array2[index];
array1[index] ^= array2[index];
index++;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.