pointers-memory · intermediate · ~15 min

Append with realloc

Grow a heap buffer and use realloc's returned pointer.

Challenge

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

Task

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.

Input

a — an n-element malloc/realloc-ed array. n — its current length. v — the value to append.

Output

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.

Example

a = {10, 20};  append(a, 2, 30)   ->   {10, 20, 30}

Rules

  • realloc may move the block, so always return and use its result.

Input format

a — n-element heap array; n — current length; v — value to append.

Output format

The (possibly moved) pointer to the n+1-element array.

Constraints

Grow with realloc; return its result since the block may move.

Starter code

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