What is the method in C language for combining two arrays?
In C language, merging two arrays usually requires creating a new array to store the combined result. Here is an example code for merging two arrays.
#include <stdio.h>
int main() {
int arr1[] = {1, 2, 3, 4, 5};
int arr2[] = {6, 7, 8, 9, 10};
int size1 = sizeof(arr1) / sizeof(arr1[0]);
int size2 = sizeof(arr2) / sizeof(arr2[0]);
int size3 = size1 + size2;
int mergedArr[size3];
// 将arr1和arr2的元素依次复制到mergedArr中
for (int i = 0; i < size1; i++) {
mergedArr[i] = arr1[i];
}
for (int i = 0; i < size2; i++) {
mergedArr[size1 + i] = arr2[i];
}
// 打印合并后的数组
for (int i = 0; i < size3; i++) {
printf("%d ", mergedArr[i]);
}
return 0;
}
Running the code above will output the merged array: 1 2 3 4 5 6 7 8 9 10. In this code snippet, we first calculate the sizes of the two arrays and create a new array mergedArr to store the merged result based on their sizes. Then we use two loops to copy elements from arr1 and arr2 into mergedArr.