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.
Java does not have dynamic arrays. Arrays in Java cannot be resized. The best you can do is create a new array with the size you want and copy the existing elements to it and discard the original. ArrayList is a class that does all this for you via an implementation of the List interface.
The length of a dynamic array is set during the allocation time. However, C++ doesn't have a built-in mechanism of resizing an array once it has been allocated. You can, however, overcome this challenge by allocating a new array dynamically, copying over the elements, then erasing the old array.
A dynamic array is a random access, variable-size list data structure that allows elements to be added or removed. It is supplied with standard libraries in many modern programming languages. Dynamic arrays overcome a limit of static arrays, which have a fixed capacity that needs to be specified at allocation.
Once an array has been allocated, there is no built-in mechanism for resizing it in the C++ programming language. Therefore, we can avoid this problem by dynamically generating a new array, copying over the contents, and then deleting the old array.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With