From f8b4f4410586ab0274d142a68758078c692c7025 Mon Sep 17 00:00:00 2001 From: Patrick Pelissier Date: Sun, 15 Aug 2021 21:44:36 +0200 Subject: [PATCH] Add ARRAY_INIT_VALUE --- README.md | 14 ++++++++++++++ m-array.h | 6 ++++++ tests/test-marray.c | 7 +++++++ 3 files changed, 27 insertions(+) diff --git a/README.md b/README.md index 1ab8fc95..7c34250a 100644 --- a/README.md +++ b/README.md @@ -1479,6 +1479,20 @@ are provided. Return the oplist of the array defined by calling ARRAY\_DEF with name & oplist. If there is no given oplist, the default oplist for standard C type is used. +#### ARRAY\_INIT\_VALUE() + +Define an initial value that is suitable to initialize global variable(s) +of the type associated to the (array) oplist 'oplist'. +It enables to create an array as a global variable and to initialize it. + +The array should still be cleared manually to avoid leaking memory. + +Example: + + ARRAY_DEF(array_int_t, int) + array_int_t my_array = ARRAY_INIT_VALUE(); + + #### Created methods In the following methods, name stands for the name given to the macro. diff --git a/m-array.h b/m-array.h index bfaf4e1e..d895ed6e 100644 --- a/m-array.h +++ b/m-array.h @@ -53,6 +53,12 @@ (__VA_ARGS__ ))) +/* Define an init value to init global variables of type array. + USAGE: + array_t global_variable = ARRAY_INIT_VALUE(array_oplist); + */ +#define ARRAY_INIT_VALUE() \ + { { 0, 0, NULL } } /********************************************************************************/ /********************************** INTERNAL ************************************/ diff --git a/tests/test-marray.c b/tests/test-marray.c index 768eb454..e7fb3c18 100644 --- a/tests/test-marray.c +++ b/tests/test-marray.c @@ -41,6 +41,8 @@ ARRAY_DEF(array_ulong, uint64_t) ARRAY_DEF_AS(array_double, ArrayDouble, ArrayDoubleIt, double) #define M_OPL_ArrayDouble() ARRAY_OPLIST(array_double, M_DEFAULT_OPLIST) +ArrayDouble g_array = ARRAY_INIT_VALUE(); + static void test_uint(void) { array_uint_t v; @@ -362,6 +364,11 @@ static void test_double(void) ref += 1.0; } } + + assert( array_double_empty_p(g_array)); + array_double_push_back(g_array, 34.); + assert( array_double_size(g_array) == 1); + array_double_clear(g_array); } int main(void)