-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathvector.h
76 lines (69 loc) · 1.94 KB
/
vector.h
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
#ifndef VECTOR_H
#define VECTOR_H
#include <stddef.h>
#include <stdlib.h>
#include <string.h>
/**
* @brief A dynamic array implementation for storing elements.
*/
typedef struct {
char** data; /**< Pointer to the underlying data array */
size_t size; /**< Number of elements in the vector */
size_t capacity; /**< Capacity of the vector */
} vector_t;
/**
* @brief Initializes a new vector.
* @return Pointer to the newly initialized vector.
*/
static inline vector_t* vector_init() {
vector_t* vector = malloc(sizeof(vector_t));
if (vector == NULL) {
return NULL;
}
vector->data = NULL;
vector->size = 0;
vector->capacity = 0;
return vector;
}
/**
* @brief Adds an element to the vector.
* @param vector Pointer to the vector.
* @param element The element to be added.
*/
static inline void vector_push(vector_t* vector, const char* element) {
if (vector->size == vector->capacity) {
size_t new_capacity = (vector->capacity == 0) ? 1 : vector->capacity * 2;
char** new_data = realloc(vector->data, new_capacity * sizeof(char*));
if (new_data == NULL) {
return;
}
vector->data = new_data;
vector->capacity = new_capacity;
}
vector->data[vector->size] = strdup(element);
vector->size++;
}
/**
* @brief Retrieves an element from the vector at a specific index.
* @param vector Pointer to the vector.
* @param index The index of the element to retrieve.
* @return The element at the specified index, or NULL if the index is out of range.
*/
static inline char* vector_get(vector_t* vector, size_t index) {
if (index >= vector->size) {
return NULL;
}
return vector->data[index];
}
/**
* @brief Frees the memory allocated for the vector.
* @param vector Pointer to the vector to be destroyed.
*/
static inline void vector_destroy(vector_t* vector) {
for (size_t i = 0; i < vector->size; i++) {
free(vector->data[i]);
}
free(vector->data);
free(vector);
}
#endif /* VECTOR_H */