Search code examples
arrayscpointersdynamic-memory-allocationc-strings

Dynamic array of pointers


I have an array of pointers to strings.

char **array; 

I declare it this way and not char *array[N] because this array won't have a static number of elements.

Declaring the array this way, I will probably have to realloc the sizeof it every time I add a new element (pointer to string).

int main(void)
{
    char **array;

    char *word = "lolol";
    char *word2 = "blabla";

    return 0;
}

Could you give me an example on how I should "create space" in the array in order to store pointers to these strings?


Solution

  • The best way of doing it is probably by making a struct

    This way, you can resize it, and add as many strings as you want without needing to choose a specific size.

    Note: setting the string_array's capacity and size to 0 is necessary for it to work.

    You could do it by a function like this instead:

    void load_array(string_array *array)
         {
         array->size = 0;
         array->capacity = 0;
         }
    

    And call it like this:

    load_array(&my_array);
    

    Note, when getting the value from one of these arrays using [], you must call it like this:

    my_array.arr[index]
    

    This is because you must refer to the pointer in the array struct, which is as arr (char **)

    I have tested the below, and it works perfectly.

    # include <stdio.h>
    
    typedef struct string_array
        {
        char **arr;
        unsigned capacity, size;
        } string_array;
    
    void add_to_array(string_array *array, char *str)
        {
        if(array->capacity == 0)
            {
            array->arr = (char **)malloc((array->capacity = 3) * sizeof(char *));
            array->arr[array->size++] = str;
            }
        else if(array->capacity == array->size)
            {
            array->arr = (char **)realloc(array->arr, (array->capacity *= 1.5) * sizeof(char *));
            array->arr[array->size++] = str;
            }
        else
            {
            array->arr[array->size++] = str;
            }
        }
    
    int main(void)
        {
        char *str1 = "Hello World";
        char *str2 = "Hello World2";
        char *str3 = "Hello World3";
        char *str4 = "Hello World4";
        char *str5 = "Hello World5";
        string_array my_array;
        my_array.capacity = 0;
        my_array.size = 0;
        add_to_array(&my_array, str1);
        add_to_array(&my_array, str2);
        add_to_array(&my_array, str3);
        add_to_array(&my_array, str4);
        add_to_array(&my_array, str5);
        // and so on
        for (int i = 0; i < my_array.size; ++i)
            {
            printf(my_array.arr[i]);
            printf("\n");
            }
        free(my_array.arr);
        getchar(); // this means pressing enter closes the console
        return (0);
        }