Dynamically create an array of strings with malloc

前端 未结 4 2062
孤城傲影
孤城傲影 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:06

    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-up
    free(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 array
    free(orderedIds);
    // Clear-up raw array
    free(raw);
    
    0 讨论(0)
  • 2020-11-28 06:08
    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]);
    }
    
    0 讨论(0)
  • 2020-11-28 06:13
    
    #define ID_LEN 5
    char **orderedIds;
    int i;
    int variableNumberOfElements = 5; /* Hard coded here */
    
    orderedIds = (char **)malloc(variableNumberOfElements * (ID_LEN + 1) * sizeof(char));
    
    ..
    
    
    0 讨论(0)
  • 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"

    0 讨论(0)
提交回复
热议问题