C++20 sections · 1024 units
Open in Course

Resizing Dynamic Arrays Manually

Grow and shrink

You can't resize an array allocated with new[]. To grow it, allocate a larger array, copy elements over, then delete the old array. This is tedious and error-prone. The resize process: new larger array, copy all elements with a loop, delete[] old array, update pointer to new array.

Miss any step and you leak memory or lose data. std::vector does this automatically. When you push_back beyond capacity, it allocates a larger buffer, copies elements, and frees the old one.

You never write this code yourself.