How to Dynamically Resize a C++ Array?
Last Updated :
06 Mar, 2024
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
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++
#include <algorithm>
#include <iostream>
using namespace std;
int main()
{
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;
int newSize = 10;
int * newArr = new int [newSize];
copy(arr, arr + size, newArr);
delete [] arr;
arr = newArr;
cout << "Resized array: " ;
for ( int i = 0; i < newSize; i++) {
cout << arr[i] << " " ;
}
cout << endl;
return 0;
}
|
Output
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.
Share your thoughts in the comments
Please Login to comment...