pointers-memory · intermediate · ~15 min

Duplicate an array

Allocate and copy into heap memory.

Challenge

Make an independent heap copy of an array, so the caller gets its own buffer to modify and free.

Task

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.

Input

a — pointer to the source int array. n — the number of elements to copy.

Output

Returns a new malloc-ed int* (distinct from a) holding a copy of the n elements. The caller frees it.

Example

int src[] = {3, 1, 4, 1, 5};
dup_array(src, 5)   ->   {3, 1, 4, 1, 5}   (a separate block, src != copy)

Rules

  • The copy is a separate heap block; the caller frees it.

Input format

a — source int array; n — element count to copy.

Output format

A new malloc-ed copy of the n elements (caller frees).

Constraints

Return a separate heap block; the caller frees it.

Starter code

#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.