I am trying to create an array of strings in C using malloc
. The number of strings that the array will hold can change at run time, but the length of the strings will always be consistent.
I've attempted this (see below), but am having trouble, any tips in the right direction will be much appreciated!
#define ID_LEN 5
char *orderedIds;
int i;
int variableNumberOfElements = 5; /* Hard coded here */
orderedIds = malloc(variableNumberOfElements * (ID_LEN + 1));
Ultimately I want to be able to use the array to do this:
strcpy(orderedIds[0], string1);
strcpy(orderedIds[1], string2);
/* etc */
Given that your strings are all fixed-length (presumably at compile-time?), you can do the following:
A more cumbersome, but more general, solution, is to assign an array of pointers, and psuedo-initialising them to point at elements of a raw backing array:
You should assign an array of char pointers, and then, for each pointer assign enough memory for the string:
Seems like a good way to me. Although you perform many mallocs, you clearly assign memory for a specific string, and you can free one block of memory without freeing the whole "string array"