Skip to the content of the web site.

Project W.4: Shirnk and resize

The shrink function takes an array and strips off all the trailing entries that are zero. It dynamically allocates a new array of the appropriate capacity, copies over the entries up to the last non-zero entry, deletes the array that was passed, and returns the dynamically allocated array. If the last entry is non-zero, just return the address of the passed array.

The resize function dynamically allocates a new array of the new capacity, copies over the entries from the old array, filling in extra entries with 0, deletes the old array, and then returns the address of the dynamically allocated array. If the new capacity is equal to the old capacity, just return the address of the passed array.

Integer implementation

int *shrink( int *array, std::size_t capacity );
int *resize( int *array, std::size_t capacity, std:size_t new_capacity );

Templated implementation

For templated implementations, you could compare to or use 0 as the default value, but it is better to compare to or use the default value of the templated type: T{}.

template <typename T>
T *shrink( T *array, std::size_t capacity );

template <typename T>
T *resize( T *array, std::size_t capacity, std:size_t new_capacity );