我想將兩個數組中的元素複製到第三個中。
我不明白爲什麼它不起作用。
我確信這兩個數組是正確填充的,但出於某種原因,實際的複製不起作用 - 當我打印arr3
的元素時,我會得到一些隨機數。C語言複製數組 - 代碼錯誤
#include <stdio.h>
int main()
{
int arr1[10], arr2[10], arr3[20];
int i, n;
printf("Enter a number of elements to be stored in each array (up to 10): ");
scanf("%d", &n);
printf("Enter the %d elements to the first array:\n", n);
for (i = 0; i < n; i++)
{
printf("Element %d: ", i + 1);
scanf("%d", &arr1[i]);
}
printf("Enter the %d elements to the second array:\n", n);
for (i = 0; i < n; i++)
{
printf("Element %d: ", i + 1);
scanf("%d", &arr2[i]);
}
/*
// A test to make sure first 2 array are filled by the user- works
for(i = 0; i < n; i++)
printf("%d ", arr1[i]);
for(i = 0; i < n; i++)
printf("%d ", arr2[i]);
*/
// something wrong here, the elements are not coppied to the third array
for(i = 0; i < n; i++);
arr3[i] = arr1[i];
for(i = n; i < 2 * n; i++)
arr3[i] = arr2[i];
for(i = 0; i < 2 * n; i++)
printf("%d\n", arr3[i]);
return(0);
}
'ARR3 [I] = ARR2 [I];':arr2'的'下標應從'0'啓動。 – BLUEPIXY
'#include memcpy(arr3,arr1,n * sizeof(* arr1)); memcpy(arr3 + n,arr2,n * sizeof(* arr2));' –
BLUEPIXY
注意一個額外的(不正確的)分號! – Olaf