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.
views:
750answers:
4
+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
2009-02-22 22:07:47
Dang. Full implementation too. Thanks a lot epatel.
Ross Rogers
2009-02-22 22:20:20
+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
2009-02-22 22:09:30
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
2009-02-22 22:12:30