diff options
author | Tavian Barnes <tavianator@tavianator.com> | 2019-09-02 16:39:54 -0400 |
---|---|---|
committer | Tavian Barnes <tavianator@tavianator.com> | 2019-09-02 16:39:54 -0400 |
commit | 325b37b290dda53392a22c7f2ef802f581e4232d (patch) | |
tree | 3850f42644b6478046c687fba33605b6174e3ab0 | |
parent | 1b79831aa6af05807bed5fb2e864b250877e1fe1 (diff) | |
download | bfs-325b37b290dda53392a22c7f2ef802f581e4232d.tar.xz |
darray: Clarify some documentation/comments
-rw-r--r-- | darray.c | 8 | ||||
-rw-r--r-- | darray.h | 33 |
2 files changed, 26 insertions, 15 deletions
@@ -22,8 +22,15 @@ * The darray header. */ struct darray { + /** The current capacity of the array, as a count of elements. */ size_t capacity; + /** The current length of the array. */ size_t length; + + // The array elements are stored after this header in memory. Not using + // a flexible array member to avoid worrying about strict aliasing. We + // assume that 2*sizeof(size_t) keeps any memory allocation suitably + // aligned for the element type. }; /** Get the header for a darray. */ @@ -83,6 +90,7 @@ int darray_check(void *da) { if (header->length <= header->capacity) { return 0; } else { + // realloc() failed in darray_push(), so reset the length and report the failure header->length = header->capacity; return -1; } @@ -17,27 +17,30 @@ /** * A dynamic array library. * - * int ret = 0; - * int *array = NULL; + * darrays are represented by a simple pointer to the array element type, like + * any other array. Behind the scenes, the capacity and current length of the + * array are stored along with it. NULL is a valid way to initialize an empty + * darray: * - * int e = 1; - * if (DARRAY_PUSH(&array, &e) != 0) { - * goto fail; - * } + * int *darray = NULL; + * + * To append an element to a darray, use the DARRAY_PUSH macro: * - * e = 2; - * if (DARRAY_PUSH(&array, &e) != 0) { - * goto fail; + * int e = 42; + * if (DARRAY_PUSH(&darray, &e) != 0) { + * // Report the error... * } * - * for (size_t i = 0; i < darray_length(array); ++i) { - * assert(array[i] == i + 1); + * The length can be retrieved by darray_length(). Iterating over the array + * works like normal arrays: + * + * for (size_t i = 0; i < darray_length(darray); ++i) { + * printf("%d\n", darray[i]); * } * - * ret = 0; - * fail: - * darray_free(array); - * return ret; + * To free a darray, use darray_free(): + * + * darray_free(darray); */ #ifndef BFS_DARRAY_H |