Resizing a Dynamic Array in C++
In C++, the size of an array is static, but we can also create a dynamic array in C++ using the new and delete operators. However, there is no direct method to specifically resize these dynamic arrays. To do that, we have to allocate a new memory block of the new size, copy all the elements of the previous array, and then delete the previous array.
Approach
- Create a new array with the desired size.
- Use the
std::copy
function from the<algorithm>
library to copy the elements from the old array to the new one. - When all the elements are copied, delete the old array to free up the memory it was using.
- Finally, assign the pointer of the old array to the new array.
C++ Program to Resize a Dynamic Array in C++
The below example demonstrates how we can dynamically resize an array in C++.
C++
// C++ Program to illustrate how to dynamically resize an // array #include <algorithm> #include <iostream> using namespace std; int main() { // Initialize an int array int * arr = new int [5]{ 10, 20, 30, 40, 50 }; int size = 5; cout << "Original array: " ; for ( int i = 0; i < size; i++) { cout << arr[i] << " " ; } cout << endl; // create new array of the new size int newSize = 10; int * newArr = new int [newSize]; // copy all the elements copy(arr, arr + size, newArr); // deallocate the previous array and assing the pointer // to the previous array to the new one delete [] arr; arr = newArr; // printing array cout << "Resized array: " ; for ( int i = 0; i < newSize; i++) { cout << arr[i] << " " ; } cout << endl; return 0; } |
Original array: 10 20 30 40 50 Resized array: 10 20 30 40 50 0 0 0 0 0
Time Complexity: O(N)
Auxiliary Space: O(N), here N is the new size after resizing
Note: The above method is not recommended if you want to perform frequent resizing because it has high time complexity. For such cases use std::vector which handles resizing automatically.
How to Dynamically Resize a C++ Array?
In C++, an array is a collection of elements of the same type placed in contiguous memory locations. In this article, we will learn how to dynamically resize an array in C++.
Example:
Input:
myArray = {10, 20, 30, 40, 50};
Output:
Resized array: 10 20 30 40 50 0 0 0 0 0
Contact Us