From aa61b5178ede9c40896885997a8d2fce2b6fee86 Mon Sep 17 00:00:00 2001 From: Stefan 'psYchotic' Zwanenburg Date: Fri, 31 Oct 2008 01:07:18 +0100 Subject: [PATCH] Did some more tweaking to make it look like GLib modified: myarray.c modified: myarray.h --- myarray.c | 15 ++++++++++----- myarray.h | 13 ++++++++----- 2 files changed, 18 insertions(+), 10 deletions(-) diff --git a/myarray.c b/myarray.c index 7bc2738..cbb83c8 100644 --- a/myarray.c +++ b/myarray.c @@ -3,12 +3,13 @@ #include #include "myarray.h" -MArray myarray_create(int size, int incr) { +MArray myarray_new(int size, int incr, int elsize) { MArray myarray = malloc(sizeof(struct myarray)); myarray->elements = calloc(size, sizeof(void *)); myarray->len = 0; myarray->maxlen = size; myarray->incr = incr; + myarray->elsize = elsize; return myarray; } @@ -26,10 +27,9 @@ void _myarray_insert(MArray array, void *element, int index) { } if (array->len == array->maxlen) { myarray_enlarge(array); - } - if (index == array->len) { - myarray_append(array, element); } else { + void *val = malloc(array->elsize); + memcpy(val, element, array->elsize); memmove(&array->elements[index+1], &array->elements[index], (array->len - index)*sizeof(void *)); array->elements[index] = element; array->len += 1; @@ -37,11 +37,16 @@ void _myarray_insert(MArray array, void *element, int index) { } void myarray_remove_index(MArray array, int index) { + free(array->elements); memmove(&array->elements[index], &array->elements[index+1], (array->len - index - 1)*sizeof(void *)); array->len--; } -void myarray_unset(MArray array) { +void myarray_free(MArray array) { + int i; + for (i = 0; i < array->len; i++) { + free(myarray_get(array, void *, i)); + } free(array->elements); free(array); } diff --git a/myarray.h b/myarray.h index 3e41458..d96abc4 100644 --- a/myarray.h +++ b/myarray.h @@ -1,24 +1,27 @@ #ifndef _MYARRAY_H #define _MYARRAY_H +#include + typedef struct myarray { void **elements; int len; int maxlen; int incr; + int elsize; } *MArray; -MArray myarray_create(int size, int incr); +MArray myarray_new(int, int, int); #define myarray_append(a,e) _myarray_insert((a), &(e), (a)->len - 1) #define myarray_insert(a,e,i) _myarray_insert((a), &(e), (i)) -void _myarray_insert(MArray array, void *element, int index); +void _myarray_insert(MArray, void *, int); #define myarray_get(a,t,i) ((t) (a)->elements[(i)]) -void myarray_remove_index(MArray array, int index); +void myarray_remove_index(MArray, int); -void myarray_reset(MArray array); +void myarray_reset(MArray); -void myarray_unset(MArray array); +void myarray_free(MArray); #endif -- 2.11.4.GIT