make cx_array_simple_add() automatically take the address of the element

Sun, 18 Feb 2024 13:16:38 +0100

author
Mike Becker <universe@uap-core.de>
date
Sun, 18 Feb 2024 13:16:38 +0100
changeset 832
97df2e4c68fb
parent 831
7970eac1c598
child 833
5c926801f052

make cx_array_simple_add() automatically take the address of the element

src/cx/array_list.h file | annotate | diff | comparison | revisions
tests/test_list.c file | annotate | diff | comparison | revisions
--- a/src/cx/array_list.h	Sun Feb 18 13:01:09 2024 +0100
+++ b/src/cx/array_list.h	Sun Feb 18 13:16:38 2024 +0100
@@ -61,6 +61,18 @@
     size_t name##_capacity;
 
 /**
+ * Initializes an array declared with cx_array_declare().
+ *
+ * The memory for the array is allocated with stdlib malloc().
+ * @param array the array
+ * @param capacity the initial capacity
+ */
+#define cx_array_initialize(array, capacity) \
+        array##_capacity = capacity; \
+        array##_size = 0; \
+        array = malloc(sizeof(array[0]) * capacity);
+
+/**
  * Defines a reallocation mechanism for arrays.
  */
 struct cx_array_reallocator_s {
@@ -181,7 +193,7 @@
  * @param size a pointer to the size of the target array
  * @param capacity a pointer to the target array's capacity - must not be \c NULL
  * @param elem_size the size of one element
- * @param elem the element to add
+ * @param elem a pointer to the element to add
  * @param reallocator the array reallocator to use, or \c NULL if reallocation shall not happen
  * @return zero on success, non-zero error code on failure
  */
@@ -192,10 +204,10 @@
  * Convenience macro that uses cx_array_add() with a default layout and the default reallocator.
  *
  * @param array the name of the array (NOT a pointer to the array)
- * @param elem the element to add
+ * @param elem the element to add (NOT a pointer, address is automatically taken)
  */
 #define cx_array_simple_add(array, elem) \
-    cx_array_simple_copy(array, array##_size, elem, 1)
+    cx_array_simple_copy(array, array##_size, &(elem), 1)
 
 /**
  * Swaps two array elements.
--- a/tests/test_list.c	Sun Feb 18 13:01:09 2024 +0100
+++ b/tests/test_list.c	Sun Feb 18 13:16:38 2024 +0100
@@ -74,7 +74,7 @@
         CX_TEST_ASSERT(stackarray_size == 5);
         CX_TEST_ASSERT(stackarray_capacity == 5);
 
-        result = cx_array_simple_add(heaparray, &elem);
+        result = cx_array_simple_add(heaparray, elem);
         CX_TEST_ASSERT(result == CX_ARRAY_SUCCESS);
         CX_TEST_ASSERT(heaparray[0] == 2);
         CX_TEST_ASSERT(heaparray[1] == 3);
@@ -85,7 +85,7 @@
         CX_TEST_ASSERT(heaparray_capacity == 5);
 
         heaparray_size = 5;
-        result = cx_array_simple_add(heaparray, &elem2);
+        result = cx_array_simple_add(heaparray, elem2);
         CX_TEST_ASSERT(result == CX_ARRAY_SUCCESS);
         CX_TEST_ASSERT(heaparray[0] == 2);
         CX_TEST_ASSERT(heaparray[1] == 3);

mercurial