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
  • 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. Commented Nov 17, 2019 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. Commented Nov 17, 2019 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.) Commented Nov 17, 2019 at 23:03
  • 1
    @DaveM. -- try to use malloc and realloc with std::strings, and see how well it works out for you. Commented Nov 17, 2019 at 23:04
  • 1
    Possible duplicate of Create an array when the size is a variable not a constant Commented Nov 17, 2019 at 23:10

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Removing several problems, adding IO checking, and utilizing standard-defined member functions and/or operators (wth is _Equal ??), the code would look like this.
@WhozCraig living and learning, I liked the for like a foreach and I forgot the operator !=, thanks.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.