C - 通过迭代位置合并两个数组

时间:2016-12-13 10:03:28

标签: c arrays

我将两个数组合并为一个问题,但我需要将一个元素放在一个,所以我有以下内容:

arr1[0] = 1; arr2[0] = 12;
arr1[1] = 2; arr2[1] = 20;
arr1[2] = 3; arr2[2] = 30;
arr1[3] = 4; arr2[3] = 40;
arr1[4] = 5; arr2[4] = 50;
arr1[5] = 6; arr2[5] = 60;
arr1[6] = 7; arr2[6] = 70;
arr1[7] = 8; arr2[7] = 80;
arr1[8] = 9; arr2[8] = 90;
arr1[9] = 11;arr2[9] = 100;

我需要将它们合并到第3个数组" arr3"通过排序如下:

  

arr3 = [1,12,2,20,3,30,4,40,5,50,6,60,7,70,8,80,9,90,11,100]

这是我制作的代码,但它仍无法正常工作:

#include <stdio.h>


int main(void) {
    int arr1[10], arr2[10], arr3[20], i,k,r;

    arr1[0] = 1; arr2[0] = 12; 
    arr1[1] = 2; arr2[1] = 20;
    arr1[2] = 3; arr2[2] = 30;
    arr1[3] = 4; arr2[3] = 40;
    arr1[4] = 5; arr2[4] = 50;
    arr1[5] = 6; arr2[5] = 60;
    arr1[6] = 7; arr2[6] = 70;
    arr1[7] = 8; arr2[7] = 80;
    arr1[8] = 9; arr2[8] = 90;
    arr1[9] = 11;arr2[9] = 100;

    for(i=0; i<20; i++){

        if(arr3[i-1] != 0){
            arr3[i] = arr1[i];
            arr3[i+1] = 0;
        } else {
            arr3[i-1] = arr2[i-1];
        }
        i++;

    }
    for(k=0; k<20; k++){
        printf("arr - %d b: %d \n", k, arr3[k]);
    }

    return 0;
}

3 个答案:

答案 0 :(得分:3)

试试这个。

int i, j;
for (i = 0, j = 0; i < 10; i++) {
    arr3[j++] = arr1[i];
    arr3[j++] = arr2[i];
}

希望这有帮助! :)

答案 1 :(得分:3)

for (int i = 0; i < 10; i++){
    arr3[i*2] = arr1[i];
    arr3[i*2 + 1] = arr2[i];
}

Try it here!

您的代码有一些失败:

for(i=0; i<20; i++){

    if(arr3[i-1] != 0){      // if i==0 you read arr3[-1] which is undefined behaviour
        arr3[i] = arr1[i];
        arr3[i+1] = 0;
    } else {
        arr3[i-1] = arr2[i-1];
    }
    i++;  // you have 2 times i++, one here and one in your for

}

如果要检查某些元素是否为0,则必须将数组初始化为零:

arr3[20] = {0};

否则你的if将永远是未定义的行为,因为i总是因为双i++而且你总是用arr3[i-1] != 0检查未初始化的不均匀元素。

答案 2 :(得分:1)

    ****Try this:**
    int i,j;
    for(i = 0,j = 0;j <10,i < 20;i+=2,j++)
    {
        arr3[i] = arr1[j];
        arr3[i + 1] = arr2[j]; 
    }**

**

  

****通过实施此功能,您可以在O(n)时间内快速完成更大规模的数据插入。****

**