-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcvec_float.c
57 lines (52 loc) · 1.18 KB
/
cvec_float.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
55
56
57
#include "cvec_float.h"
#include <assert.h>
#include <stdlib.h>
#include <string.h>
cvec_float *cvec_float_alloc(size_t cap) {
assert(cap > 0);
cvec_float *temp = malloc(sizeof(cvec_float));
if (!temp) {
return NULL;
}
temp->size = 0;
temp->capacity = cap;
temp->arr = malloc(sizeof(float) * cap);
if (!temp->arr) {
free(temp);
return NULL;
}
return temp;
}
int cvec_float_push(cvec_float *l, float val) {
if (l->capacity > l->size) {
l->arr[l->size++] = val;
return 0;
}
size_t new_cap = l->capacity * 2;
float *temp = realloc(l->arr, new_cap * sizeof(float));
if (!temp)
return 1;
l->arr = temp;
l->arr[l->size++] = val;
l->capacity = new_cap;
return 0;
}
void cvec_float_pop(cvec_float *l) { l->size--; }
void cvec_float_free(cvec_float *l) {
free(l->arr);
free(l);
}
cvec_float *cvec_float_copy_alloc(cvec_float *l) {
cvec_float *temp = malloc(sizeof(cvec_float));
if (!temp)
return NULL;
temp->size = l->size;
temp->capacity = l->capacity;
temp->arr = malloc(sizeof(float) * temp->capacity);
if (!temp->arr) {
free(temp);
return NULL;
}
memcpy(temp->arr, l->arr, sizeof(float) * l->size);
return temp;
}