C++ Notes: Example - Dynamic C-String Allocation

This example shows dynamic allocation to allocate arrays of the correct size. The problem is how to read and save "words". The solution here is to have an array of pointers to the words, dynamically allocat space for each word. A rectangular 2-dimensional array would be very inefficient because each row would be as long as the longest possible word, therefore this array of arrays solution is better. There are more efficient solutions for this particular problem, but this easily generalizes to applications other than simply listed the words in reverse order. This program is similar in structure to the (better) string and vector solution.

  1 
  2 
  3 
  4 
  5 
  6 
  7 
  8 
  9 
 10 
 11 
 12 
 13 
 14 
 15 
 16 
 17 
 18 
 19 
 20 
 21 
 22 
 23 
 24 
 25 
 26 
 27 
 28 
 29 
 30 
 31 
 32 
 33 
 34 
 35 
 36 
 37 
 38 
 39 
 40 
 41 
 42 
 43 
// Program to read words and print in reverse order.
// Illustrates use of new keyword to dynamically allocate
//     space for each of the strings that are read in.
//     If the variation in "word" size is very large,
//     dynamic allocation is the only reasonable solution.
// What this program doesn't do, but should, is reallocate
//     the word and allwords arrays to make them expand
//     as needed.  Currently it is subject to buffer overflows.
// Fred Swartz 2001-11-08

#include <iostream>
using namespace std;

int main() {

    char *wordList[1000];   // array of POINTERS to char strings
    char inputBuffer[1000]; // input area for longest possible word.
    int n = 0;              // count of number of words and index.

    //--- read words/tokens from input stream
    while (cin >> inputBuffer) {
        int len = strlen(inputBuffer);    // length of word just read
        wordList[n] = new char[len+1];    // allocate space for word
        strcpy(wordList[n], inputBuffer); // copy word to new space
        n++;
    }

    cout << "Hello?" << endl;  // Hmmm, this line disappears.
    cout << "Number of words = " << n << endl;

    // --- Write the words in reverse order.
    for (int i=n-1; i>=0; i--) {
        cout << wordList[i] << endl; // print the word
        
        // Delete dynamically allocated space when no longer needed.
        // The pointer is set to NULL to prevent accidental use of it.
        // This isn't necessary here because the program terminates.
        // But it's good practice, and makes bug detection easier.
        delete [] wordList[i];       // free space
        wordList[i] = NULL;          // remove pointer
    }
    return 0;
}//end main
This program doesn't dynamically expand the arrays it uses so is subject to the buffer overflow problem in both the wordList and inputBuffer arrays. Fixing this is left as an exercise.