pointers-memory · intermediate · ~15 min
Grow a heap buffer and use realloc's returned pointer.
Grow a heap array by one element with realloc and store a new value in the freed-up slot, returning the pointer (which may have moved).
Implement int *append(int *a, int n, int v) that reallocs the n-element heap array a to n+1 elements, writes v into the new last slot (index n), and returns the resulting pointer. No main — the grader calls it.
a — an n-element malloc/realloc-ed array. n — its current length. v — the value to append.
Returns the (possibly relocated) pointer to the n+1-element array, with v at index n. The caller adopts the returned pointer and frees it.
a = {10, 20}; append(a, 2, 30) -> {10, 20, 30}
realloc may move the block, so always return and use its result.a — n-element heap array; n — current length; v — value to append.
The (possibly moved) pointer to the n+1-element array.
Grow with realloc; return its result since the block may move.
#include <stdlib.h>
int *append(int *a, int n, int v) {
/* TODO */
return a;
}
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.