Skip to content

Instantly share code, notes, and snippets.

@Leyka
Last active March 5, 2019 03:20
Show Gist options
  • Save Leyka/ee947c0d2ebc5502cb84ddb12b81272d to your computer and use it in GitHub Desktop.
Save Leyka/ee947c0d2ebc5502cb84ddb12b81272d to your computer and use it in GitHub Desktop.
Dynamic list in C
/*
* Dynamic List
* Reference: https://eddmann.com/posts/implementing-a-dynamic-vector-array-in-c
*/
#include <stdlib.h>
#define LIST_DEFAULT_CAPACITY 10
typedef struct list {
void **items;
int size;
int capacity;
} List;
void list_init(List *l)
{
l->capacity = LIST_DEFAULT_CAPACITY;
l->items = malloc(l->capacity * sizeof(void*));
l->size = 0;
}
int list_size(List *l)
{
return l->size;
}
static int list_index_valid(List *l, int index)
{
return index >= 0 && index < l->size;
}
static void list_resize(List *l, int capacity)
{
void** items = realloc(l->items, capacity * sizeof(void*));
if (items) {
l->items = items;
l->capacity = capacity;
}
}
void list_add(List *l, void *item)
{
// Size check before add
if (l->size == l->capacity) {
list_resize(l, l->capacity * 2);
}
l->items[l->size] = item;
l->size++;
}
void* list_get(List *l, int index)
{
if (!list_index_valid(l, index)) {
return NULL;
}
return l->items[index];
}
void list_set(List *l, int index, void* item)
{
if (!list_index_valid(l, index)) {
return;
}
l->items[index] = item;
}
void list_remove(List *l, int index)
{
if (!list_index_valid(l, index)) {
return;
}
l->items[index] = NULL;
l->size--;
// Relink next items
for (int i = index; i < l->size; i++) {
l->items[i] = l->items[i+1];
l->items[i+1] = NULL;
}
// Check if we can downsize list
if (l->size == l->capacity / 4) {
list_resize(l, l->capacity / 2);
}
}
void list_free(List *l)
{
free(l->items);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment