pointers-memory · intermediate · ~18 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 on success or -1 on failure; see the contract below. After a successful nonzero resize, *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).

Why this matters

Drill: practice one contract before combining it with other skills.

Input format

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

Output format

Returns newn on success or -1 on failure; see the contract below. After a successful nonzero resize, *a points to the resized block and the first min(oldn, newn) values are preserved. The caller frees *a.

Constraints

a is a valid pointer to the owner; oldn matches its current nonnegative length. newn=0 frees *a, sets it to NULL, and returns 0. Invalid sizes or failure return -1 with *a unchanged. Success returns newn and transfers the new pointer through a; added elements are uninitialized.

Starter code

#include <stdlib.h>

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

Common mistakes

Replacing *a on failure; assuming new elements are zero; relying on realloc(p,0).

Edge cases to handle

Grow, shrink, same size, NULL/zero old allocation, zero new size, negative new size, forced failure.

Up next

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