C程序 将一个数组的所有元素复制到另一个数组
用C语言将一个数组的所有元素复制到另一个数组,有三种方法。
示例:
输入:
First Array: a[5] = {3, 6, 9, 2, 5}
输出:
First Array : a[5] = {3, 6, 9, 2, 5}
Second Array : b[5] = {3, 6, 9, 2, 5}
解释: 从数组a复制元素到b,然后打印第二个数组元素
方法1:简单地将元素从一个数组复制到另一个数组
// C program to copy all the elements
// of one array to another
#include <stdio.h>
int main()
{
int a[5] = { 3, 6, 9, 2, 5 }, n = 5;
int b[n], i;
// copying elements from one array to another
for (i = 0; i < n; i++) {
b[i] = a[i];
}
// displaying first array before
// copy the elements from
// one array to other
printf("The first array is :");
for (i = 0; i < n; i++) {
printf("%d ", a[i]);
}
// displaying array after copy
// the elements from one
// array to other
printf("\nThe second array is :");
for (i = 0; i < n; i++) {
printf("%d ", b[i]);
}
return 0;
}
输出
The first array is :3 6 9 2 5
The second array is :3 6 9 2 5
方法2:使用函数
// C program to copy all the elements
// of one array to another using functions
#include <stdio.h>
int copy_array(int* a, int* b, int n)
{
int i;
// copying elements from
// one array to another
for (i = 0; i < n; i++) {
b[i] = a[i];
}
// displaying array after copy
// the elements from one
// array to other
for (i = 0; i < n; i++) {
printf("%d ", b[i]);
}
}
// displaying first array before
// copy the elements from one
// array to other
int first_array(int* a, int n)
{
int i;
for (i = 0; i < n; i++) {
printf("%d ", a[i]);
}
}
int main()
{
int k[5] = { 3, 6, 9, 2, 5 }, n = 5;
int l[n];
printf("The first array is : ");
first_array(k, n);
printf("\nThe second array is : ");
copy_array(k, l, n);
return 0;
}
输出
The first array is : 3 6 9 2 5
The second array is : 3 6 9 2 5
方法3:使用递归
// C program to copy all the elements
// of one array to another using recursion
#include <stdio.h>
int copy_array(int a[], int b[], int n, int i)
{
// copying elements from one array to another
if (i < n) {
b[i] = a[i];
copy_array(a, b, n, ++i);
}
}
int array(int a[], int n)
{
int i;
for (i = 0; i < n; i++) {
printf("%d ", a[i]);
}
}
int main()
{
int k[5] = { 3, 6, 9, 2, 5 }, n = 5;
int l[n], i;
copy_array(k, l, n, 0);
// displaying first array before
// copy the elements from
// one array to other
printf("first array : ");
array(k, n);
// displaying array after copy
// the elements from one
// array to other
printf("\nsecond array : ");
array(l, n);
return 0;
}
输出
first array : 3 6 9 2 5
second array : 3 6 9 2 5