blob: 4ebb67e18431448e153820348d64adb1404b7a45 (
plain)
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
43
44
45
46
47
|
#include "../include/array.h"
#include "../include/helpers.h"
#include <stdlib.h>
array_t *init_array() {
array_t *a = safe_calloc(1, sizeof(array_t));
a->capacity = DEFAULT_ARR_LEN;
a->size = 0;
a->items = safe_calloc(a->capacity, sizeof(void *));
return a;
}
void array_push(array_t *a, void *item) {
if (a->size >= a->capacity - 2) {
a->capacity *= 2;
a->items = realloc(a->items, a->capacity);
}
a->items[a->size] = item;
a->size++;
}
void *array_pop(array_t *a) {
if (a->size <= 0)
return NULL;
void *retval = a->items[a->size];
a->size--;
return retval;
}
array_t *array_reverse(array_t *a) {
array_t *reverse = init_array();
for (int i = 0; i < a->size; i ++) {
array_push(reverse, array_pop(a));
}
array_free(a, nothing);
return reverse;
}
void array_free(void *x, void (*freefunc)(void *)) {
array_t *a = (array_t *)x;
for (int i = 0; i < a->size; i++) {
freefunc(a->items[i]);
}
free(a->items);
free(a);
}
|