James James - 3 months ago 35
C++ Question

How to allocate a string array in C++?

I'm learning C++ and made myself a text file with over 10,000 lines. I'm trying to make a string array and insert the first line into the first array, the second line into the second array and so on. Here is what I've done so far:

ifstream theFile;
string inputFile;
cin >> inputFile;
const unsigned int ARRAY_CAP = 64U;

string line;
string *lineArr = new string[ARRAY_CAP];

if (theFile.is_open()) {
int lineNumber = 0;
while (!theFile.eof()) {
getline(theFile, line);
lineArr[i] = line;

A friend of mine told me to allocate the string array because I'm running out of memory, but I'm not even sure how to do that. How could I be able to allocate the string array?


If you want to stay with dynamically allocated arrays, you will need to expand them dynamically.

unsigned int lines_read = 0U;
std::string text_line;
unsigned int capacity = 4U;
std::string * p_array = new std::string[capacity];
while (std::getline(theFile, text_line))
  p_array[lines_read] = text_line;
  if (lines_read > capacity)
     // Allocate new array with greater capacity.
     unsigned int old_capacity = capacity;
     capacity = capacity * 2U;
     std::string p_new_array = new std::string[capacity];
     std::copy(p_array, p_array + old_capacity, p_new_array);
     delete [] p_array;
     p_array = p_new_array;

The std::vector performs similar memory management for you, so you don't have to do the above.