mirror of
https://github.com/bkthomps/Containers.git
synced 2025-11-16 12:34:47 +00:00
Add zero length arrays (#28)
This commit is contained in:
12
src/array.c
12
src/array.c
@@ -34,7 +34,8 @@ struct internal_array {
|
||||
/**
|
||||
* Initializes an array.
|
||||
*
|
||||
* @param element_count the amount of elements in the array; must be positive
|
||||
* @param element_count the amount of elements in the array; must not be
|
||||
* negative
|
||||
* @param data_size the size of each element in the array; must be positive
|
||||
*
|
||||
* @return the newly-initialized array, or NULL if memory allocation error
|
||||
@@ -42,7 +43,7 @@ struct internal_array {
|
||||
array array_init(const int element_count, const size_t data_size)
|
||||
{
|
||||
struct internal_array *init;
|
||||
if (element_count <= 0 || data_size == 0) {
|
||||
if (element_count < 0 || data_size == 0) {
|
||||
return NULL;
|
||||
}
|
||||
init = malloc(sizeof(struct internal_array));
|
||||
@@ -51,6 +52,10 @@ array array_init(const int element_count, const size_t data_size)
|
||||
}
|
||||
init->bytes_per_item = data_size;
|
||||
init->item_count = element_count;
|
||||
if (init->item_count == 0) {
|
||||
init->data = NULL;
|
||||
return init;
|
||||
}
|
||||
init->data = calloc((size_t) element_count, data_size);
|
||||
if (!init->data) {
|
||||
free(init);
|
||||
@@ -79,6 +84,9 @@ int array_size(array me)
|
||||
*/
|
||||
void array_copy_to_array(void *const arr, array me)
|
||||
{
|
||||
if (me->item_count == 0) {
|
||||
return;
|
||||
}
|
||||
memcpy(arr, me->data, me->item_count * me->bytes_per_item);
|
||||
}
|
||||
|
||||
|
||||
10
tst/array.c
10
tst/array.c
@@ -7,6 +7,7 @@ void test_array(void)
|
||||
int i;
|
||||
int *data;
|
||||
int arr[10] = {0};
|
||||
int array[2] = {0xdeadbeef, 0xdeadbeef};
|
||||
int get;
|
||||
assert(!array_init(-1, sizeof(int)));
|
||||
assert(!array_init(1, 0));
|
||||
@@ -42,4 +43,13 @@ void test_array(void)
|
||||
assert(array_get(&get, me, -1) == -EINVAL);
|
||||
me = array_destroy(me);
|
||||
assert(!me);
|
||||
me = array_init(0, sizeof(int));
|
||||
assert(array_size(me) == 0);
|
||||
array_copy_to_array(array, me);
|
||||
assert(array[0] == 0xdeadbeef);
|
||||
assert(array[1] == 0xdeadbeef);
|
||||
assert(!array_get_data(me));
|
||||
assert(array_set(me, 0, &get) == -EINVAL);
|
||||
assert(array_get(&get, me, 0) == -EINVAL);
|
||||
assert(!array_destroy(me));
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user