Advertisement
Guest User

Untitled

a guest
Apr 7th, 2020
145
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.81 KB | None | 0 0
  1. int rows = 0;
  2.     int columns = 0;
  3.     int currentRowStorage = 5;
  4.  
  5.     char*** rowStringsPointer = nullptr;
  6.  
  7.     for (std::string line; std::getline(std::cin, line);) {
  8.         // Set the number of columns from the first line and initialise an array
  9.         // of 5 rows
  10.         if (columns == 0) {
  11.             columns = line.length();
  12.             char** newRowArray = new char*[currentRowStorage];
  13.             for (int i = 0; i < currentRowStorage; ++i) {
  14.                 newRowArray[i] = new char[columns + 1];
  15.             }
  16.             rowStringsPointer = &newRowArray;
  17.         }
  18.  
  19.         // If the current array of rows is too small to add another
  20.         if (rows + 1 > currentRowStorage) {
  21.             // create a new array with capacity of old array + 5
  22.             char** newRowArray = new char*[currentRowStorage + 5];
  23.  
  24.             // initialise each row as an empty array of column number of chars
  25.             for (int i = 0; i < currentRowStorage + 5; ++i) {
  26.                 newRowArray[i] = new char[columns + 1];
  27.             }
  28.  
  29.             // copy all rows from old array to new one and delete old rows
  30.             for (int i = 0; i < currentRowStorage; ++i) {
  31.                 newRowArray[i] = *rowStringsPointer[i];
  32.                 delete *rowStringsPointer[i];
  33.             }
  34.  
  35.             // delete old array
  36.             delete *rowStringsPointer;
  37.  
  38.             // update pointer to point to new array
  39.             rowStringsPointer = &newRowArray;
  40.         }
  41.  
  42.         // create a new char array of length columns then copy the characters
  43.         // from this line string
  44.         char row[columns + 1];
  45.         line.copy(row, columns + 1);
  46.         row[columns + 1] = '\0';
  47.  
  48.         // add new row to array and increment rows counter
  49.         *rowStringsPointer[rows] = row;
  50.         ++rows;
  51.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement