Change myarray_insert to allow for appending now.
[myarray.git] / myarray.c
blob3ed14715099f88c667c80df81c965287f1e0def8
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 if (index < 0 || index > array->len) {
24 fprintf(stderr, "Array index out of bounds %s:%d. Index: %d. Array size: %d\n", __FILE__, __LINE__, index, array->len);
25 exit(EXIT_FAILURE);
27 if (array->len == array->maxlen) {
28 myarray_enlarge(array);
29 } else {
30 void *val = malloc(array->elsize);
31 memcpy(val, element, array->elsize);
32 memmove(&array->elements[index+1], &array->elements[index], (array->len - index)*sizeof(void *));
33 array->elements[index] = element;
34 array->len += 1;
38 void myarray_remove_index(MArray array, int index) {
39 free(array->elements);
40 memmove(&array->elements[index], &array->elements[index+1], (array->len - index - 1)*sizeof(void *));
41 array->len--;
44 void myarray_free(MArray array) {
45 int i;
46 for (i = 0; i < array->len; i++) {
47 free(myarray_get(array, void *, i));
49 free(array->elements);
50 free(array);
53 void myarray_reset(MArray array) {
54 array->len = 0;