I have allocated a string array in CPP with initial size and I need to dynamically resize it based on a counter.
This the initialization statement: string buffer[10]; I need to resize it based on a counter. Is there a realloc function in cpp?
I have allocated a string array in CPP with initial size and I need to dynamically resize it based on a counter.
This the initialization statement: string buffer[10]; I need to resize it based on a counter. Is there a realloc function in cpp?
You should use something like a linked list such as std::vector
or std::list
to do so, here is an example:
#include <iostream>
#include <stdlib.h>
#include <string>
#include <list>
using namespace std;
int main()
{
list<string> buffer;
int count = 0;
while (true)
{
string s;
cin >> s;
if (s._Equal("exit"))
break;
buffer.push_back(s);
count++;
}
cout << endl << endl << "We have a total of " << count << " string(s):";
for (auto i = buffer.begin(); i != buffer.end(); i++)
cout << endl << "- " << (*i).c_str();
cout << endl << endl;
system("pause");
return 0;
}
link: std::vector
std::vector is a sequence container that encapsulates dynamic size arrays.