我有2个阵列:
array1[] = {1,2,3,4};
array2[] = {5,6,7,8};
我尝试将它们合并到第3个数组中:
merge[] = {};
我的脚本目前输出:
1 2 3 4 3 4 3 4
而不是:
1 2 3 4 五 6 7 8
无法解决循环条件的问题:
#include<stdio.h>
int main() {
printf("\n\n");
int array1[] = {1,2,3,4};
int array2[] = {5,6,7,8};
int merge[] = {};
int n1, n2, n3, i;
//size of arrays
n1 = sizeof(array1)/sizeof(array1[0]);
n2 = sizeof(array2)/sizeof(array2[0]);
n3 = n1 + n2;
printf("The value of n1 is %d\n", n1);
printf("sum of array1 & array2 lengths is %d\n\n", n3);
for(int i = 0 ; i < n1; i++){
merge[i] = array1[i];
printf("%d\n", merge[i]);
};
for(int i = n1 ; i < n3; i++){
merge[i] = array2[i-n1];
printf("%d\n", merge[i]);
};
printf("\n\n");
return 0;
};
我尝试将merge声明为:
int merge[8] = {0,0,0,0,0,0,0,0};
这很有效。
原始问题中的问题 - 声明一个没有元素的空数组:merge [] = {}; 但仍然不确定为什么输出是1 2 3 4 3 4 3 4.
答案 0 :(得分:2)
首先计算n1,n2&amp; n3然后用n3创建合并数组,那么你不需要硬编码长度。我已根据需要更新您的代码。
#include<stdio.h>
int main() {
printf("\n\n");
int array1[] = {1,2,3,4};
int array2[] = {5,6,7,8};
int n1, n2, n3, i;
//size of arrays
n1 = sizeof(array1)/sizeof(array1[0]);
n2 = sizeof(array2)/sizeof(array2[0]);
n3 = n1 + n2;
int merge[n3];
printf("The value of n1 is %d\n", n1);
printf("sum of array1 & array2 lengths is %d\n\n", n3);
for(int i = 0 ; i < n1; i++){
merge[i] = array1[i];
printf("%d\n", merge[i]);
};
for(int i = n1 ; i < n3; i++){
merge[i] = array2[i-n1];
printf("%d\n", merge[i]);
};
printf("\n\n");
return 0;
};
我希望这是你所期待的。