Dynamically create an array of strings with malloc

前端 未结 4 2070
孤城傲影
孤城傲影 2020-11-28 05:23

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 string

4条回答
  •  醉话见心
    2020-11-28 06:16

    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"

提交回复
热议问题