How do I dynamically allocate an array of strings in C?

前端 未结 4 852
生来不讨喜
生来不讨喜 2020-12-05 08:49

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

4条回答
  •  -上瘾入骨i
    2020-12-05 09:20

    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.

提交回复
热议问题