Skip to content

Commit 7ce0de3

Browse files
author
Heitor Danilo
committed
refactor: adding a initializer function
1 parent e62f99a commit 7ce0de3

File tree

1 file changed

+49
-0
lines changed

1 file changed

+49
-0
lines changed

src/token/array_operations.c

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
#include <stdlib.h>
2+
3+
#include <token/lib.h>
4+
5+
/**
6+
* Initializes a dynamic array of tokens.
7+
*
8+
* @return A pointer to the newly created token array.
9+
*/
10+
struct Tokens *new_tokens_array() {
11+
struct Tokens *tokens_array = (struct Tokens *)malloc(sizeof(struct Tokens));
12+
13+
tokens_array->capacity = 10;
14+
tokens_array->size = 0;
15+
tokens_array->tokens = (struct Token **)malloc(tokens_array->capacity * sizeof(struct Token *));
16+
17+
return tokens_array;
18+
}
19+
20+
/**
21+
* Pushes a token to a dynamic array of tokens.
22+
*
23+
* @param array The token array.
24+
* @param token The token to be added.
25+
*/
26+
void push_token(struct Tokens *array, struct Token *token) {
27+
if (array->size == array->capacity) {
28+
array->capacity *= 2;
29+
array->tokens = (struct Token **)realloc(array->tokens,
30+
array->capacity * sizeof(struct Token *));
31+
}
32+
33+
array->tokens[array->size] = token;
34+
array->size++;
35+
}
36+
37+
/**
38+
* Deallocates the memory used by the token array and all its tokens.
39+
*
40+
* @param array The token array to be deallocated.
41+
*/
42+
void pop_tokens(struct Tokens *array) {
43+
for (size_t i = 0; i < array->size; i++) {
44+
free(array->tokens[i]);
45+
}
46+
47+
free(array->tokens);
48+
free(array);
49+
}

0 commit comments

Comments
 (0)