c-preprocessor/char_dyn_arr.c

68 lines
966 B
C

// SPDX-License-Identifier: BSD-2
#include "char_dyn_arr.h"
#include <errno.h>
#include <stdlib.h>
struct char_dyn_arr *init_char_dyn_arr(int size)
{
struct char_dyn_arr *a;
a = NULL;
a = calloc(1, sizeof(struct char_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:
free(a);
free(a->data);
return NULL;
}
int insert_char_dyn_arr(struct char_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_char_dyn_arr(struct char_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);
}