arrayscdynamicdynamic-arraysc-libraries

Is there a standard C library for dynamic arrays?


One of the greatest things about Python is the flexibility of dynamic arrays (lists).

It's so useful I find it hard to believe there isn't a library for this already included in C. This question indicates that there is no standard library for this. Apparently, glibc includes functionality for queues, but as I'm on a windows machine this is not helpful. As the question is 10 years old, I'm wondering if there's been an update.

Is implementing the functionality yourself still the only way to get something like a Python list or is there a standard C library that allows you to use dynamic arrays?


Solution

  • C language has something which is called flexible array members:

    typedef struct 
    {
        size_t size;
        size_t used; 
        int data[];
    }int_arr;
    
    
    int_arr *addsize(int_arr *arr, size_t inc)
    {
        size_t newsize = 0;
        size_t newused = 0;
    
        if(arr)
        {
            newsize = arr -> size + inc;
            newused = arr -> used;
        }
        arr = realloc(arr, sizeof(*arr) + newsize * sizeof(arr -> data[0]));
        if(arr)
        {
            arr -> size = newsize;
            arr -> used = newused;
        }
        return arr;
    }