back to scratko.xyz
summaryrefslogtreecommitdiff
path: root/dynamic_array.c
blob: 5a24cb8619584f0fef7c675659474a98a1e27876 (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
#include "dynamic_array.h"
#include <stdlib.h>

void dynarr_create_array(struct dynamic_array *array)
{
    array->arr = calloc(initial_size, 1);
    array->last_element_index = -1;
    array->allocation_size = initial_size;
}

static void dynarr_allocate_memory(struct dynamic_array *array)
{
    char *new_arr = calloc(array->allocation_size * 2, 1);
    dynarr_copy_array(array, new_arr);
    free(array->arr);
    array->arr = new_arr;
    array->allocation_size *= 2;
}

void dynarr_push_back(struct dynamic_array *array, int letter)
{
    if(array->last_element_index+1 == array->allocation_size)
        dynarr_allocate_memory(array);
    ++array->last_element_index;
    array->arr[array->last_element_index] = letter;
}
void dynarr_copy_array(struct dynamic_array *array, char *new_arr)
{
    int i;
    for(i = 0; i <= array->last_element_index; ++i)
        new_arr[i] = array->arr[i];
}

void dynarr_drop_word(struct dynamic_array *array)
{
    array->last_element_index = -1;
}

void dynarr_clear(struct dynamic_array *array)
{
    free(array->arr);
    array->arr = NULL;
}