C++ Notes: Dynamic Allocation of C-Strings

Problem: How to store an array of C-strings

A typical problem is how to store an array of C-strings. C-strings are arrays of chars terminated by a zero value. How do we create an array of C-strings?

Possible Solution: Array of C-string Pointers

One 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];   // Temporary place to hold input string.
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 in array.
    n++;
}
. . .

Another Solution: Two-dimensional array

Because C-strings are arrays, an array of C-strings could be implemented as a two-dimensional array. This approach may be attractive if the strings are all close in size, because the row length must accomodate the longest string.