From 7213af916cbb0087a6b85c800311c3f6a60c13b3 Mon Sep 17 00:00:00 2001 From: ZoRo Date: Sat, 4 Aug 2018 09:36:29 +0100 Subject: Added dynamic array --- darray.c | 141 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 141 insertions(+) create mode 100644 darray.c (limited to 'darray.c') diff --git a/darray.c b/darray.c new file mode 100644 index 0000000..4df4064 --- /dev/null +++ b/darray.c @@ -0,0 +1,141 @@ +#include "darray.h" + +#include "debug.h" + +DArray::DArray(size_t data_size, size_t init_size) +{ + int i; + + if (init_size <= 0) + { + goto error; + } + + this->_max = init_size; + this->data = (void **)malloc(init_size*sizeof(void *)); + this->end = 0; + //this->size = data_size; + this->_expand = DEFAULT_EXPAND_RATE; + + +error:; +} + +DArray::~DArray() +{ + +} + +int DArray::push(void *val) +{ + if (this->data[this->end] != NULL) + { + ENL(); + } + + this->data[this->end] = val; + this->end++; + + if (this->end > this->_max) + { + return this->expand(); + } + + return 0; +} + +int DArray::expand() +{ + size_t old_max = this->_max; + + if (this->resize(this->_max + DEFAULT_EXPAND_RATE)) + { + goto error; + } + + memset(this->data + old_max, 0, this->_expand+1); + return 0; + +error: + ENL(); + return -1; +} + +int DArray::resize(size_t size) +{ + int i = 0; + void *data = NULL; + + if (size < 1) + { + ENL(); + goto error; + } + + if (size < this->_max) + { + i = this->_max; + do + { + if (this->data[i-1] != NULL) + { + free(this->data[i-1]);//??? is there is some data then free it? + this->data[i-1] = NULL; + } + i -= 1; + } while (i-1 == size); + } + this->_max = size; + + data = (void **)realloc(this->data, this->_max * sizeof(void*)); + if (data == NULL) + { + ENL(); + goto error; + } + + this->data = (void **)data; + return 0; + +error: + ERROR("\n"); + return -1; +} + +int DArray::set(int idx, void *val) +{ + if (idx > this->_max) + { + ENL(); + return -1; + } + + if (idx>this->end) + { + this->end = idx; + } + + this->data[idx] = val; + + return 0; +} + +void* DArray::get(int idx) +{ + if (idx<0) + { + return NULL; + } + + if (idx>=this->end) + { + return NULL; //??? + } + + return this->data[idx]; +} + +int DArray::count() +{ + return this->end; +} -- cgit v1.2.3