pointers-memory · intermediate · ~15 min
Allocate and copy into heap memory.
Make an independent heap copy of an array, so the caller gets its own buffer to modify and free.
Implement int *dup_array(const int *a, int n) that returns a freshly malloc-ed copy of the first n elements of a. No main — the grader calls it and frees the result.
a — pointer to the source int array. n — the number of elements to copy.
Returns a new malloc-ed int* (distinct from a) holding a copy of the n elements. The caller frees it.
int src[] = {3, 1, 4, 1, 5};
dup_array(src, 5) -> {3, 1, 4, 1, 5} (a separate block, src != copy)
a — source int array; n — element count to copy.
A new malloc-ed copy of the n elements (caller frees).
Return a separate heap block; the caller frees it.
#include <stdlib.h>
#include <string.h>
int *dup_array(const int *a, int n) {
/* TODO */
return NULL;
}
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.