views:

750

answers:

4

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.

+4  A: 

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);
epatel
Dang. Full implementation too. Thanks a lot epatel.
Ross Rogers
+1  A: 

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.

schnaader
i was hoping to avoid re-inventing the wheel. what a shame. I'm sure the wrappering you're talking about happens all the time.
Ross Rogers
Perhaps there is some library for it, but most of them are for C++...
schnaader
:-) Alright. I'll use realloc. Thanks for the quick response.
Ross Rogers
No problem, that's what SO is for :)
schnaader
+2  A: 

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.

vinc456
+1  A: 

You can also use obstacks

dmityugov