Dynamically create an array of strings with malloc Dynamically create an array of strings with malloc arrays arrays

Dynamically create an array of strings with malloc


You should assign an array of char pointers, and then, for each pointer assign enough memory for the string:

char **orderedIds;orderedIds = malloc(variableNumberOfElements * sizeof(char*));for (int i = 0; i < variableNumberOfElements; i++)    orderedIds[i] = malloc((ID_LEN+1) * sizeof(char)); // yeah, I know sizeof(char) is 1, but to make it clear...

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"


char **orderIds;orderIds = malloc(variableNumberOfElements * sizeof(char*));for(int i = 0; i < variableNumberOfElements; i++) {  orderIds[i] = malloc((ID_LEN + 1) * sizeof(char));  strcpy(orderIds[i], your_string[i]);}


Given that your strings are all fixed-length (presumably at compile-time?), you can do the following:

char (*orderedIds)[ID_LEN+1]    = malloc(variableNumberOfElements * sizeof(*orderedIds));// Clear-upfree(orderedIds);

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:

char *raw = malloc(variableNumberOfElements * (ID_LEN + 1));char **orderedIds = malloc(sizeof(*orderedIds) * variableNumberOfElements);// Set each pointer to the start of its corresponding section of the raw buffer.for (i = 0; i < variableNumberOfElements; i++){    orderedIds[i] = &raw[i * (ID_LEN+1)];}...// Clear-up pointer arrayfree(orderedIds);// Clear-up raw arrayfree(raw);