简体   繁体   中英

Merge 2 arrays into empty 3rd array in C

I have 2 arrays:

array1[] = {1,2,3,4}; 
array2[] = {5,6,7,8};

And I try to merge them into a 3rd array:

merge[] = {};

My script currently output:

1 2 3 4 3 4 3 4

Instead of:

1 2 3 4 5 6 7 8

Can't figure out the problem with my loop conditions:

#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;
};

Update

I try to declare merge as:

int merge[8] = {0,0,0,0,0,0,0,0};

This works.

The problem in the original question- declaring an empty array with no elements in it: merge[] = {}; but still not sure why the output was 1 2 3 4 3 4 3 4.

First calculate n1, n2 & n3 then create Merge Array with n3 then you don't need to hard code the length. I have update your code as needed.

#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;
};

I hope this is what you are expecting.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM