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.
_Equal ??), the code would look like this.
std::vector, for a more complete explanation of how this needs to be done.reallocfunction in c++. You can't use it to reallocate an automatic variable (a variable allocated on the stack, as OP appears to be doing it) but you could definitely allocate an array of strings, and then reallocate it. (It's messier than just using astd::vector, but OP's instructor may be teaching the old-fashioned messy way first, before showing the easy, modern way.)std::strings, and see how well it works out for you.