# HG changeset patch # User Mike Becker # Date 1573119811 -3600 # Node ID 07ac32b385e45aa6035bf296e3898fc32ada8b8c # Parent 28a8ccc442b03eeb1a296139ead0e0bf64c6442c updates the web doc for array diff -r 28a8ccc442b0 -r 07ac32b385e4 docs/src/modules.md --- a/docs/src/modules.md Thu Nov 07 10:10:36 2019 +0100 +++ b/docs/src/modules.md Thu Nov 07 10:43:31 2019 +0100 @@ -61,22 +61,17 @@ a standard dynamic C array (pointer+length) as basis. ```C -#include -#include -#include -#include - -UcxArray remove_duplicates(sstr_t* array, size_t arrlen) { +UcxArray* create_unique(sstr_t* array, size_t arrlen) { // worst case is no duplicates, hence the capacity is set to arrlen - UcxArray result = ucx_array_new(arrlen, sizeof(sstr_t)); + UcxArray* result = ucx_array_new(arrlen, sizeof(sstr_t)); // only append elements, if they are not already present in the array for (size_t i = 0 ; i < arrlen ; ++i) { if (!ucx_array_contains(result, array+i, ucx_cmp_sstr, NULL)) { - ucx_array_append(&result, array+i); + ucx_array_append_from(result, array+i, 1); } } // make the array as small as possible - ucx_array_shrink(&result); + ucx_array_shrink(result); return result; } @@ -85,16 +80,36 @@ sstr_t* array = /* some standard array of strings */ size_t arrlen = /* the length of the array */ -UcxArray result = remove_duplicates(array,arrlen); +UcxArray* result = create_unique(array,arrlen); /* Iterate over the array and print the elements */ -for (size_t i = 0 ; i < result.size ; i++) { - sstr_t s = ucx_array_at_typed(sstr_t, result, i); - printf("%" PRIsstr "\n", SFMT(s)); +sstr_t* unique = result->data; +for (size_t i = 0 ; i < result->size ; i++) { + printf("%" PRIsstr "\n", SFMT(unique[i])); } /* Free the array. */ -ucx_array_free(&result); +ucx_array_free(result); +``` +### Preventing out of bounds writes + +The functions `ucx_array_reserve()`, `ucx_array_resize()`, `ucx_array_grow()`, +and `ucx_array_shrink()` allow easy management of the array capacity. +Imagine you want to add `n` elements to an array. If your `n` elements are +already somewhere else consecutively in memory, you can use +`ucx_array_append_from()` and benefit from the autogrow facility in this family +of functions. Otherwise, you can ask the array to have enough capacity for +holding additional `n` elements. + +```C +size_t n = // ... elements to add +if (ucx_array_grow(array, n)) { + fprintf(stderr, "Cannot add %zu elements to the array.\n", n); + return 1; +} +for (size_t i = 0 ; i < n ; i++) { + ((int*)array->data)[array->size++] = 80; +} ``` ## AVL Tree