Is there an auto-resizing array/dynamic array implementation for C that comes with glibc?

时光怂恿深爱的人放手 提交于 2019-11-30 16:38:52

问题


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



来源:https://stackoverflow.com/questions/575914/is-there-an-auto-resizing-array-dynamic-array-implementation-for-c-that-comes-wi

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!