-
Notifications
You must be signed in to change notification settings - Fork 1
/
array.c
34 lines (29 loc) · 622 Bytes
/
array.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
#include <assert.h>
#include "array.h"
struct array*
new_array(size_t capacity) {
struct array* a = malloc(sizeof(*a));
a->capacity = capacity;
a->size = 0;
a->items = malloc(sizeof(*a->items) * a->capacity);
return a;
}
void
array_add(struct array* a, void* item) {
if (a->size >= a->capacity) {
a->capacity *= 2;
a->items = realloc(a->items, sizeof(*a->items) * a->capacity);
}
a->items[a->size] = item;
a->size += 1;
}
void*
array_get(struct array* a, size_t index) {
assert(index >= 0 && index < a->size);
return a->items[index];
}
void
destroy_array(struct array* a) {
free(a->items);
free(a);
}