pointers-memory · intermediate · ~16 min
Allocate exactly the combined size and copy both inputs.
Join two arrays into one freshly allocated heap array: all of the first, followed by all of the second.
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.
a/na — first array and its length. b/nb — second array and its length.
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.
a = {1, 2}, b = {3, 4, 5}
concat_arrays(a, 2, b, 3) -> {1, 2, 3, 4, 5}
na + nb ints; copy b starting at offset na. The caller frees the result.Drill: practice one contract before combining it with other skills.
a/na — first array and its length. b/nb — second array and its length.
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.
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.
#include <stdlib.h>
#include <string.h>
int *concat_arrays(const int *a, int na, const int *b, int nb) {
/* TODO */
return NULL;
}
Copying b at the wrong offset, freeing borrowed input, or forgetting one branch of cleanup.
Either array empty; both empty; ordering and negative elements; source independence; allocation failure.
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.