Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 965
Ross Rogers Avatar asked Feb 22 '09 22:02

Ross Rogers


People also ask

How do you resize an array dynamically?

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.

How do you dynamically resize an array in C++?

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.

What is dynamic array explain its concept with the help of a program?

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.

How do I reduce the size of an array in C++?

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.


1 Answers

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);
like image 65
epatel Avatar answered Sep 22 '22 08:09

epatel