-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstrarr_util.c
69 lines (56 loc) · 1.2 KB
/
strarr_util.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
58
59
60
61
62
63
64
65
66
67
68
69
#include "strarr_util.h"
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void add_str_to_strarr(const char *str, const char ***arr, size_t *arrlen)
{
if (NULL == (*arr = realloc(*arr, sizeof(const char *) * (*arrlen + 1)))) {
return;
}
if (NULL == ((*arr)[*arrlen] = malloc(strlen(str) + 1))) {
return;
}
strcpy((char *)(*arr)[*arrlen], str);
*arrlen = *arrlen + 1;
}
void remove_str_from_strarr(const char *str, const char ***arr, size_t *arrlen)
{
size_t index = 0;
int found = 0;
for (index = 0; index < *arrlen; ++index) {
if (strcmp((*arr)[index], str) == 0) {
found = 1;
break;
}
}
if (!found) {
return;
}
const char **newarr;
if (NULL == (newarr = malloc((*arrlen - 1) * sizeof(const char *)))) {
return;
}
// Copy elements, skipping the element to remove
for (size_t i = 0, j = 0; i < *arrlen; ++i) {
if (i != index) {
newarr[j++] = (*arr)[i];
}
}
if (*arr) {
free((void *)(*arr)[index]);
free(*arr);
}
errno = 0;
*arrlen = *arrlen - 1;
*arr = newarr;
}
int strarr_contains(const char **strs, size_t len, const char *str)
{
for (int i = 0; i < len; i++) {
if (strcmp(strs[i], str) == 0) {
return 1;
}
}
return 0;
}