-
Notifications
You must be signed in to change notification settings - Fork 0
/
vector.c
54 lines (42 loc) · 1013 Bytes
/
vector.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
43
44
45
46
47
48
49
50
51
52
53
54
#include "vector.h"
#include <stdio.h>
#include <stdlib.h>
void
vector_init(Vector_p v) {
vector_init_with_capacity(v, VECTOR_INIT_CAPACITY);
}
void
vector_init_with_capacity(Vector_p v, int capacity) {
v->size = 0;
v->capacity = capacity;
v->data = malloc(sizeof(int) * v->capacity);
}
void
vector_append(Vector_p v, int value) {
if (v->size >= v->capacity) {
v->capacity *= 2;
v->data = realloc(v->data, sizeof(int) * v->capacity);
}
v->data[v->size++] = value;
}
int
vector_get(Vector_p v, int index) {
if (index < 0 || index >= v->size) {
printf("Index %d out of bounds for v of size %d\n", index, v->size);
perror("Index out of bounds");
return 0;
}
return v->data[index];
}
void
vector_set(Vector_p v, int index, int value) {
if (index < 0 || index >= v->size) {
perror("Index out of bounds");
return;
}
v->data[index] = value;
}
void
vector_destroy(Vector_p v) {
free(v->data);
}