We're a community of 1076K IT Pros here for help, advice, solutions, professional growth and fun. Join us!
1,075,610 Members — Technology Publication meets Social Media

merge 2 arrays in a new

Hi all,
I have to make a function which take as parameter two arrays and merge in one new.

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

To take as result
arraynew[][] = {{1 , 2, 3, 4}, {2, 3, 4, 5},{5 , 6, 7, 8}, {6, 7, 8, 9};

Array1 and array2 have 4 columns but the can have more than 2 rows.

Could you help me ???

2
Contributors
3
Replies
1 Hour
Discussion Span
3 Years Ago
Last Updated
4
Views
bufospro
Junior Poster
145 posts since May 2007
Reputation Points: 14
Skill Endorsements: 0

assuming you got column size compatibility between arrays, you must create an array with `x` quantity of rows, `x` being the sum of array1's rows and array's 2 rows (I assume you know these sizes, since you had to declare the arrays sizes). After that, you create two nester for loops to go through both arrays one after another. This way:

``````int sizex = 4, sizey1 = 2; sizey2 = 3;
int array1[sizex][sizey1]={{1,2,3,4},{2,3,4,5}};
int array2[sizex][sizey2]={{3,4,5,6},{4,5,6,7},{5,6,7,8}};
int array3[sizex][sizey1+sizey2];

for (int x = 0 ; x < sizex ; x+=1)
{
for (int y = 0 ; y < sizey1 ; y+=1)
{
array3[x][y] = array1[x][y];
}
}
for (int x = 0 ; x < sizex ; x+=1)
{
for (int y = sizey1 ; y < sizey2 ; y+=1)
{
array3[x][y] = array1[x][y];
}
}``````

this way, `array3` would be:

{1,2,3,4}
{2,3,4,5}
{3,4,5,6}
{4,5,6,7}
{5,6,7,8}

Nichito
Posting Virtuoso
1,700 posts since Mar 2007
Reputation Points: 424
Skill Endorsements: 3

Thanks a lot !

bufospro
Junior Poster
145 posts since May 2007
Reputation Points: 14
Skill Endorsements: 0

remember marking solved threads as solved ;)

Nichito
Posting Virtuoso
1,700 posts since Mar 2007
Reputation Points: 424