How do I dynamically allocate an array of strings in C?

NOTE: My examples are not checking for NULL returns from malloc()… you really should do that though; you will crash if you try to use a NULL pointer.

First you have to create an array of char pointers, one for each string (char *):

char **array = malloc(totalstrings * sizeof(char *));

Next you need to allocate space for each string:

int i;
for (i = 0; i < totalstrings; ++i) {
    array[i] = (char *)malloc(stringsize+1);
}

When you’re done using the array, you must remember to free() each of the pointers you’ve allocated. That is, loop through the array calling free() on each of its elements, and finally free(array) as well.

Leave a Comment