c-preprocessor/str_dyn_arr.c

69 lines
969 B
C

/* SPDX-License-Identifier: BSD-2 */
#include "str_dyn_arr.h"
#include <errno.h>
#include <stdlib.h>
struct str_dyn_arr *init_str_dyn_arr(int size)
{
struct str_dyn_arr *a;
a = NULL;
a = calloc(1, sizeof(struct str_dyn_arr));
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:
if (a)
free(a->data);
free(a);
return NULL;
}
int insert_str_dyn_arr(struct str_dyn_arr *a, char *e)
{
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;
}
extern void free_str_dyn_arr(struct str_dyn_arr *a)
{
int i;
if (!a)
return;
if (a->data) {
for (i = 0; i < a->used; i++)
free(a->data[i]);
}
free(a->data);
free(a);
}