Is there an auto-resizing array/dynamic array impl

2019-02-11 23:54发布

问题:

Is there a dynamic array implementation in glibc or any of the standard Linux libraries for C? I want to be able to add to a list without worrying about its size. I know std::vector exists for C++, but I need the C equivalent.

回答1:

I guess you are thinking of realloc. But its better to wrap a list in a structure to keep track of its current length

Example API

struct s_dynamic_array {
    int allocated;   /* keep track of allocated size  */
    int usedLength;  /* keep track of usage           */
    int *array;      /* dynamicaly grown with realloc */
};
typedef struct s_dynamic_array s_dynamic_array;

s_dynamic_array *new_dynamic_array(int initalSize);
void             free_dynamic_array(s_dynamic_array *array);
int              size_of_dynamic_array(s_dynamic_array *array);
s_dynamic_array *add_int_to_dynamic_array(s_dynamic_array *array, int value);
int              int_at_index(s_dynamic_array *array, int index);


回答2:

There is a dynamic array in glib. (not glibc though) Check out GArray and GPtrArray. A dynamic array is not really the same thing as a linked list though.

Anyways this is the most useful resource I've been able to find when learning glib.



回答3:

I always use realloc for this, you could wrap your own array functions around it. AFAIK, there are no other built-in things for this.



回答4:

You can also use obstacks