pointers-memory · intermediate · ~15 min

Duplicate an array

Allocate and copy into heap memory.

Challenge

Implement int *dup_array(const int *a, int n) returning a freshly malloc-ed copy of the first n elements. 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.