Merging Arrays – Solution

This month’s Exercise is about coding a merge() function, which swallows two arrays and generates a third as output. The new array is “zippered” from the original arrays, alternating values from each.

My merge() function solution involves two steps.

First, allocate storage for the new array. Because both arrays are the same size; only one size value is passed as an argument:

int *merge(int *a, int *b, int s)

If the two arrays were different sizes, two size arguments are required, each paired with its array. Either way, storage is allocated for the new array, which is assumed to be an integer data type.

Second, loop through the two arrays, packing the newly-allocated array with alternating values from each of the two passed arrays. Two variables help move through the arrays: offset for the new array and index for the two passed arrays. Here is my merge() function:

int *merge(int *a, int *b, int s)
{
    int *r,offset,index;

    /* allocate maximum stroage */
    r = malloc( sizeof(int) * s * 2 );

    if( r!=NULL )
    {
        offset = index = 0;
        while( offset<s*2 )
        {
            r[offset++] = *(a+index);
            r[offset++] = *(b+index);
            index++;
        }
    }
    return(r);
}

The function returns the address of int pointer r, which is allocated as the first step. Providing the result isn’t NULL, values from each of the passed arrays, a and b, are assigned to sequential offsets in the new array.

Variable offset is incremented after each value is added to array r, but variable index is incremented only after processing both arrays a and b.

When the function is complete, address r is returned, though in the main() function I don’t test for NULL. Instead, the following statements handle the function call and the output:

    c = merge(a,b,SIZE);
    printf("Merged: ");
    for( x=0; x<SIZE*2; x++ )
        printf(" %2d",c[x]);
    putchar('\n');

Though variable c is declared as a pointer, and used in the merge() function call that way, I use array notation when c‘s values are output in the loop. This type of conversion is okay, and it keeps with the use of the other arrays in the main() function.

Click here to view the full code on GitHub. I hope your solution worked out well and that the new array shows the proper data in sequence, zippered by the merge() function.

Leave a Reply