mystring.c had a little (non-)error.
[xmlparser.git] / myarray.c
blob9bc26787b46fba0a7220bfce65bfd141a0cf4e42
1 #include <stdlib.h>
2 #include <stdio.h>
3 #include <string.h>
4 #include "myarray.h"
6 MArray myarray_new(int size, int incr, int elsize) {
7 MArray myarray = malloc(sizeof(struct myarray));
8 myarray->elements = calloc(size, sizeof(void *));
9 myarray->len = 0;
10 myarray->maxlen = size;
11 myarray->incr = incr;
12 myarray->elsize = elsize;
14 return myarray;
17 static void myarray_enlarge(MArray array) {
18 array->maxlen+= array->incr;
19 array->elements = realloc(array->elements, array->maxlen*sizeof(void *));
22 void _myarray_insert(MArray array, void *element, int index) {
23 void *toinsert = malloc(array->elsize);
24 memcpy(toinsert, element, array->elsize);
25 if (index < 0 || index > array->len) {
26 fprintf(stderr, "Array index out of bounds %s:%d. Index: %d. Array size: %d\n", __FILE__, __LINE__, index, array->len);
27 exit(EXIT_FAILURE);
29 if (array->len == array->maxlen) {
30 myarray_enlarge(array);
32 memmove(&array->elements[index+1], &array->elements[index], (array->len - index)*sizeof(void *));
33 array->elements[index] = toinsert;
34 array->len += 1;
37 void myarray_remove_index(MArray array, int index) {
38 free(array->elements[index]);
39 memmove(&array->elements[index], &array->elements[index+1], (array->len - index - 1)*sizeof(void *));
40 array->len--;
43 void myarray_free(MArray array) {
44 int i;
45 for (i = 0; i < array->len; i++) {
46 free(array->elements[i]);
48 free(array->elements);
49 free(array);
52 void myarray_reset(MArray array) {
53 array->len = 0;