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.
The common idiom for allocating an N by M array of any type T is
T **a = malloc(N * sizeof *a);
if (a)
for (i = 0; i < N; i++)
a[i] = malloc(M * sizeof *a[i]);
As of the 1989 standard, you don't need to cast the result of malloc
, and in fact doing so is considered bad practice (it can suppress a useful diagnostic if you forget to include stdlib.h or otherwise don't have a prototype for malloc
in scope). Earlier versions of C had malloc
return char *
, so the cast was necessary, but the odds of you having to work with a pre-1989 compiler are pretty remote at this point. C++ does require the cast, but if you're writing C++ you should be using the new
operator.
Secondly, note that I'm applying the sizeof
operator to the object being allocated; the type of the expression *a
is T *
, and the type of *a[i]
is T
(where in your case, T
== char
). This way you don't have to worry about keeping the sizeof
expression in sync with the type of the object being allocated. IOW, if you decide to use wchar
instead of char
, you only need to make that change in one place.