pointers-memory · intermediate · ~15 min
Allocate + copy. The motivating concept of "deep" vs "shallow" copy.
Make an independent heap copy of an int array, so mutating the copy never affects the original.
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.
src: pointer to the source array of int.n: the number of elements. May be 0.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.
copy_ints({4,5,6,7}, 4) -> new array {4,5,6,7}, independent of the source
n = 0: you may return NULL.src (this is a deep copy).NULL if allocation fails.src itself.Pointer src to an int array and a length n (n may be 0).
A new malloc'd array with the same contents, owned by the caller; NULL allowed when n is 0.
Independent copy (mutating it must not change src); the caller frees.
#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.