I've written an implementation of a dynamic array in C, but I'm not sure if my implementation is correct... This is what I'm worried about: if I add an element, will it remain in the collection? This problem has arisen from my (apparently) limited knowledge on void pointers. I haven't found any answers to my question online...
The List struct is defined like this:
typedef struct list
{
/**
* C-style array containing the data in this list.
*/
void** data;
/**
* Amount of elements currently present in this list.
*/
unsigned int size;
/**
* Amount of elements that could be present in this list (i.e. size + number of empty spots).
*/
unsigned int capacity;
} List;
So far so good?
Now, when I want to add an element to a list l
, I call List_Add(&l, &element)
...
void List_Add(List* list, void* element)
{
if (list->data == NULL)
{
return;
}
if (list->size == list->capacity)
{
// Double the data array of list.
list->data = realloc(list->data, 2 * list->capacity * sizeof(void*));
list->capacity *= 2;
}
if (list->data != NULL)
{
list->data[list->size] = element;
++(list->size);
}
}
By the way: yes, list->data is malloced before calling this function.
I've done some testing with adding elements, but I'm not sure if it's entirely correct. If I were to call this function with an element created on the stack (example below), would it continue to work for the entirety of the program's lifetime?
Example
List l;
List_Init(&l);
int i = 1;
List_Add(&l, &i);