pointers-memory · intermediate · ~15 min

Concatenate two arrays

Allocate exactly the combined size and copy both inputs.

Challenge

Join two arrays into one freshly allocated heap array: all of the first, followed by all of the second.

Task

Implement int *concat_arrays(const int *a, int na, const int *b, int nb) that returns a new heap array of na + nb ints containing the a elements followed by the b elements. No main — the grader calls it and frees the result.

Input

a/na — first array and its length. b/nb — second array and its length.

Output

Returns a malloc-ed int* of length na + nb (a then b). The caller frees it.

Example

a = {1, 2},  b = {3, 4, 5}
concat_arrays(a, 2, b, 3)   ->   {1, 2, 3, 4, 5}

Rules

  • Allocate exactly na + nb ints; copy b starting at offset na. The caller frees the result.

Input format

a/na and b/nb — two int arrays and their lengths.

Output format

A new heap array of length na + nb (a then b); caller frees.

Constraints

Allocate the combined size and copy both inputs; the caller frees it.

Starter code

#include <stdlib.h>
#include <string.h>

int *concat_arrays(const int *a, int na, const int *b, int nb) {
    /* TODO */
    return NULL;
}

Solve this exercise in the browser editor — compile and run against the test harness, no setup required.