C++ Notes: Example: Allocationing C-Strings

Example: array of C-strings

A typical problem is how to store an array of C-strings. C-strings are simply arrays of chars terminated by a zero value. It's common to read a string into an array, then save it in an array with other strings. A common solution is to declare an array of pointers to C-strings, and dynamically allocate space for each of the C-strings.
char  aWord[100];   // a temporary place to hold new word
char* words[1000];  // array of pointers to c-strings
int   n = 0;        // number of words
. . .
while (cin >> aWord) {
    int len = strlen(aWord) + 1;    // how much space is needed
    char* newSpace = new char[len]; // allocate with new
    strcpy(newSpace, aWord);        // copy to new space
    words[n] = newSpace;            // save pointer
. . .
This code is intended only to show dynamic allocation of arrays of a known size. It still has the problem that the arrays to hold the word, and the array of the character pointers are still fixed size and can not expand as needed. The expansion of arrays is shown in Array Expansion.