pointers-memory · intermediate · ~15 min

Deep-copy an int array

Allocate + copy. The motivating concept of "deep" vs "shallow" copy.

Challenge

Make an independent heap copy of an int array, so mutating the copy never affects the original.

Task

Implement int *copy_ints(const int *src, size_t n) that returns a freshly allocated array holding the same n ints as src. No main — the grader calls it.

Input

  • src: pointer to the source array of int.
  • n: the number of elements. May be 0.

Output

A pointer to a new malloc-ed array with the same contents as src. The caller frees it. If n == 0 you may return NULL.

Example

copy_ints({4,5,6,7}, 4)   ->   new array {4,5,6,7}, independent of the source

Edge cases

  • n = 0: you may return NULL.
  • Mutating the returned array must NOT change src (this is a deep copy).
  • Return NULL if allocation fails.

Rules

  • Allocate new storage and copy; do not return src itself.

Input format

Pointer src to an int array and a length n (n may be 0).

Output format

A new malloc'd array with the same contents, owned by the caller; NULL allowed when n is 0.

Constraints

Independent copy (mutating it must not change src); the caller frees.

Starter code

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

int *copy_ints(const int *src, size_t n) {
    /* TODO */
    return NULL;
}

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