How to Resize an Array of Strings in C++?
Last Updated :
01 Feb, 2024
In C++, the array of strings is useful for storing many strings in the same container. Sometimes, we need to change the size of this array. In this article, we will look at how to resize the array of strings in C++.
Resize String Array in C++
There is no way to directly resize the previously allocated memory. But we can create a new array, copy all the elements, and then delete the previous array using new and delete operators.
C++ Programs to Resize an Array in Strings
C++
#include <iostream>
using namespace std;
int main()
{
string* oldArray
= new string[5]{ "Apple" , "Banana" , "Cherry" ,
"Date" , "Fig" };
cout << "Old Array Elements:" << endl;
for ( int i = 0; i < 5; ++i) {
cout << oldArray[i] << endl;
}
int newSize = 7;
string* newArray = new string[newSize];
for ( int i = 0; i < 5; ++i) {
newArray[i] = oldArray[i];
}
newArray[5] = "kiwi" ;
newArray[6] = "dragonfruit" ;
delete [] oldArray;
cout << "New Array Elements:" << endl;
for ( int i = 0; i < newSize; ++i) {
cout << newArray[i] << endl;
}
delete [] newArray;
return 0;
}
|
Output
Old Array Elements:
Apple
Banana
Cherry
Date
Fig
New Array Elements:
Apple
Banana
Cherry
Date
Fig
kiwi
dragonfruit
Instead of this type of array we can use dynamic std::vector of strings which by default enables dynamic resizing.
Share your thoughts in the comments
Please Login to comment...