-
Notifications
You must be signed in to change notification settings - Fork 0
/
list.c
42 lines (37 loc) · 1.06 KB
/
list.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "list.h"
void init_list(list_t *list, int data_size) {
list->size = 0;
list->capacity = LIST_INITIAL_CAPACITY;
list->data_size = data_size;
list->data = malloc(sizeof(void *) * list->capacity);
}
void list_append(list_t *list, void *val) {
if (list->size >= list->capacity) {
// double list capacity
list->capacity *= 2;
list->data = realloc(list->data, list->data_size * list->capacity);
}
list->data[list->size] = malloc(list->data_size);
memcpy(list->data[list->size++], val, list->data_size);
}
void *list_get(list_t *list, int index) {
if (index >= list->size || index < 0) {
fprintf(stderr, "Index %d is out of bounds for list of size %d\n",
index, list->size);
return NULL;
}
return list->data[index];
}
void destroy_list(list_t *list) {
int i;
for (i = 0; i < list->size; i++) {
free(list->data[i]);
}
free(list->data);
}
int list_size(list_t *list) {
return list->size;
}