If I have the number of items in a var called \"totalstrings\" and a var called \"string size\" that is the string size of each item, how do I dynamically allocate an array
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.