0

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?

  • 5
    No, there isn't. Open your C++ book to the chapter that explains how to use `std::vector`, for a more complete explanation of how this needs to be done. – Sam Varshavchik Nov 17 '19 at 22:42
  • C has a realloc but you would need to use the malloc or calloc C function to allocate the array in the first place. Using C functions is for backwards compatibility only and it isn't best practice for a new C++ program to use them. The comment about using std::vector is good advice. – Jerry Jeremiah Nov 17 '19 at 22:58
  • @SamVarshavchik Of _course_ there's a `realloc` function 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 a `std::vector`, but OP's instructor may be teaching the old-fashioned messy way first, before showing the easy, modern way.) – Dave M. Nov 17 '19 at 23:03
  • 1
    @DaveM. -- try to use malloc and realloc with `std::string`s, and see how well it works out for you. – Sam Varshavchik Nov 17 '19 at 23:04
  • 1
    Possible duplicate of [Create an array when the size is a variable not a constant](https://stackoverflow.com/questions/57367473/create-an-array-when-the-size-is-a-variable-not-a-constant) –  Nov 17 '19 at 23:10

1 Answers1

1

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.

ichikuma
  • 23
  • 3
Matt
  • 53
  • 4
  • Removing several problems, adding IO checking, and utilizing standard-defined member functions and/or operators (wth is `_Equal` ??), the [code would look like this](https://ideone.com/FSOMbN). – WhozCraig Nov 17 '19 at 23:12
  • 1
    @WhozCraig living and learning, I liked the for like a foreach and I forgot the operator !=, thanks. – Matt Nov 17 '19 at 23:18