pointers-memory · intermediate · ~16 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

On success, returns a malloc-ed int* of length na + nb (a then b). The caller frees it. Return NULL for invalid/empty requests or allocation failure, as specified in the contract below.

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.

Why this matters

Drill: practice one contract before combining it with other skills.

Input format

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

Output format

On success, returns a malloc-ed int* of length na + nb (a then b). The caller frees it. Return NULL for invalid/empty requests or allocation failure, as specified in the contract below.

Constraints

Lengths are nonnegative. A source may be NULL only when its length is zero. Return NULL for an empty result, invalid inputs, size overflow, or allocation failure. Borrow both inputs; return an independent allocation owned by the caller.

Starter code

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

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

Common mistakes

Copying b at the wrong offset, freeing borrowed input, or forgetting one branch of cleanup.

Edge cases to handle

Either array empty; both empty; ordering and negative elements; source independence; allocation failure.

Up next

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