Search code examples
carraysfor-loopmerge

Combine or merge 2 array with loop or function


I'm using Visual 2010. I need to create an array from 2 other arrays, or a function to merge them; I come from PHP so I'm sorry if this is stupid. I tested some loop without success..

a real example could be helpful:

int arrayA[5] = {3,2,1,4,5} 
int arrayB[5] = {6,3,1,2,9}

And the printed expected output of the third arrayC should be :

arrayC {
[3][6]
[2][3]
[2][1]
[4][2]
[5][9]
}

Solution

  • A straightforward approach can look the following way

    #include <stdio.h>
    
    #define N   5
    
    int main( void )
    {
        int a[N] = { 3, 2, 2, 4, 5 }; 
        int b[N] = { 6, 3, 1, 2, 9 };
        int c[N][2];
    
        for ( size_t i = 0; i < N; i++ )
        {
            c[i][0] = a[i]; c[i][1] = b[i];
        }
    
        for ( size_t i = 0; i < N; i++ ) printf( "%d, %d\n", c[i][0], c[i][1] ); 
    
        return 0;
    } 
    

    The program output is

    3, 6
    2, 3
    2, 1
    4, 2
    5, 9
    

    If you want to write a function that will merge arrays of any size then it can look like

    #include <stdio.h>
    #include <stdlib.h>
    
    #define N   5
    
    int ** merge( int *a, int *b, size_t n )
    {
        int **c = malloc( n * sizeof( int * ) );
    
        if ( c != NULL )
        {
            size_t i = 0;
            for ( ; i < n && ( c[i] = malloc( 2 * sizeof( int ) ) ); i++ )
            {
                c[i][0] = a[i]; c[i][1] = b[i];
            }
    
            if ( i != n )
            {
                while ( i-- ) free( c[i] );
                free( c );
                c = NULL;
            }
        }
    
        return c;
    }   
    
    int main( void )
    {
        int a[N] = { 3, 2, 2, 4, 5 }; 
        int b[N] = { 6, 3, 1, 2, 9 };
        int **c;
    
        c = merge( a, b, N );
    
        if ( c != NULL )
        {
            for ( size_t i = 0; i < N; i++ ) printf( "%d, %d\n", c[i][0], c[i][1] ); 
            for ( size_t i = 0; i < N; i++ ) free( c[i] );
            free( c );
        }
    
        return 0;
    } 
    

    The program output will be the same as shown above.