pointers-memory · intermediate · ~15 min

Resize via a pointer-to-pointer

Resize a heap array through a double pointer and report the new size.

Challenge

Resize a heap array through a pointer-to-pointer, so the caller's pointer is updated even when realloc moves the block. Report the new element count.

Task

Implement int resize(int **a, int oldn, int newn) that reallocs *a to newn elements (preserving the first min(oldn, newn) values), writes the new block back into *a, and returns newn. No main — the grader calls it.

Input

a — the address of a heap int*. oldn — its current length. newn — the desired length.

Output

Returns newn. After the call, *a points to the resized block and the first min(oldn, newn) values are preserved. The caller frees *a.

Example

*a = {1, 2, 3};  resize(&a, 3, 2)   ->   returns 2, *a == {1, 2}
*a = {7, 8};     resize(&a, 2, 4)   ->   returns 4, *a == {7, 8, ?, ?}

Rules

  • Write the realloc result back through *a (the block may move).

Input format

a — address of a heap int*; oldn — current length; newn — desired length.

Output format

Returns newn; *a points to the resized block.

Constraints

Resize with realloc and store the result back through *a.

Starter code

#include <stdlib.h>

int resize(int **a, int oldn, int newn) {
    /* TODO */
    return 0;
}

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