pointers-memory · intermediate · ~18 min
Resize a heap array through a double pointer and report the new size.
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.
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.
a — the address of a heap int*. oldn — its current length. newn — the desired length.
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.
*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, ?, ?}
*a (the block may move).Drill: practice one contract before combining it with other skills.
a — the address of a heap int*. oldn — its current length. newn — the desired length.
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.
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.
#include <stdlib.h>
int resize(int **a, int oldn, int newn) {
/* TODO */
return 0;
}
Replacing *a on failure; assuming new elements are zero; relying on realloc(p,0).
Grow, shrink, same size, NULL/zero old allocation, zero new size, negative new size, forced failure.
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.