-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvec.c
More file actions
78 lines (69 loc) · 1.54 KB
/
vec.c
File metadata and controls
78 lines (69 loc) · 1.54 KB
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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
#include <stdlib.h>
#include "vec.h"
/* Create vector of specified length */
vec_ptr new_vec(long len)
{
/* Allocate header structure */
vec_ptr result = (vec_ptr) malloc(sizeof(vec_rec));
data_t *data = NULL;
if (!result)
return NULL; /* Couldn't allocate storage */
result->len = len;
/* Allocate array */
if (len > 0) {
data = (data_t *)calloc(len, sizeof(data_t));
if (!data) {
free((void *) result);
return NULL; /* Couldn't allocate storage */
}
}
/* data will either be NULL or allocated array */
result->data = data;
return result;
}
/* Free storage used by vector */
void free_vec(vec_ptr v) {
if (v->data)
free(v->data);
free(v);
}
/*
* Retrieve vector element and store at dest.
* Return 0 (out of bounds) or 1 (successful)
*/
int get_vec_element(vec_ptr v, long index, data_t *dest)
{
if (index < 0 || index >= v->len)
return 0;
*dest = v->data[index];
return 1;
}
/* Return length of vector */
long vec_length(vec_ptr v)
{
return v->len;
}
data_t *get_vec_start(vec_ptr v)
{
return v->data;
}
/*
* Set vector element.
* Return 0 (out of bounds) or 1 (successful)
*/
int set_vec_element(vec_ptr v, long index, data_t val)
{
if (index < 0 || index >= v->len)
return 0;
v->data[index] = val;
return 1;
}
/* Set vector length. If >= allocated length, will reallocate */
void set_vec_length(vec_ptr v, long newlen)
{
if (newlen > v->len) {
free(v->data);
v->data = (data_t*)calloc(newlen, sizeof(data_t));
}
v->len = newlen;
}