c-preprocessor/str_dyn_arr.c

69 lines
969 B
C
Raw Permalink Normal View History

2021-03-21 14:07:19 +00:00
/* SPDX-License-Identifier: BSD-2 */
2021-03-19 14:44:59 +00:00
2021-03-21 14:07:19 +00:00
#include "str_dyn_arr.h"
2021-03-19 14:44:59 +00:00
#include <errno.h>
#include <stdlib.h>
2021-03-21 14:07:19 +00:00
struct str_dyn_arr *init_str_dyn_arr(int size)
2021-03-19 14:44:59 +00:00
{
2021-03-21 14:07:19 +00:00
struct str_dyn_arr *a;
2021-03-19 14:44:59 +00:00
a = NULL;
2021-03-21 14:07:19 +00:00
a = calloc(1, sizeof(struct str_dyn_arr));
2021-03-19 14:44:59 +00:00
if (!a)
goto free_and_exit;
a->data = calloc(size, sizeof(char *));
if (!(a->data))
goto free_and_exit;
a->used = 0;
a->size = size;
return a;
free_and_exit:
2021-03-24 08:18:38 +00:00
if (a)
free(a->data);
2021-03-19 14:44:59 +00:00
free(a);
return NULL;
}
2021-03-21 14:07:19 +00:00
int insert_str_dyn_arr(struct str_dyn_arr *a, char *e)
2021-03-19 14:44:59 +00:00
{
if (a->used == a->size) {
a->size *= 2;
a->data = realloc(a->data, a->size * sizeof(char *));
if (!(a->data))
goto free_and_exit;
}
a->data[a->used++] = e;
return CHAR_DYN_ARR_OK;
free_and_exit:
free(a);
free(a->data);
return CHAR_DYN_ARR_FAILED;
}
2021-03-21 14:07:19 +00:00
extern void free_str_dyn_arr(struct str_dyn_arr *a)
2021-03-19 14:44:59 +00:00
{
int i;
if (!a)
return;
if (a->data) {
for (i = 0; i < a->used; i++)
free(a->data[i]);
}
free(a->data);
free(a);
}