6 MArray
myarray_new(int size
, int incr
, int elsize
) {
7 MArray myarray
= malloc(sizeof(struct myarray
));
8 myarray
->elements
= malloc(size
* elsize
);
10 myarray
->maxlen
= size
;
12 myarray
->elsize
= elsize
;
13 myarray
->cmpfunc
= NULL
;
18 void myarray_set_cmpfunc(MArray array
, int (*cmpfunc
)(void *, void *)) {
19 array
->cmpfunc
= cmpfunc
;
22 void myarray_enlarge(MArray array
) {
23 array
->maxlen
+= array
->incr
;
24 array
->elements
= realloc(array
->elements
, array
->maxlen
*array
->elsize
);
27 void _myarray_insert(MArray array
, void *element
, int index
) {
28 if (index
< 0 || index
> array
->len
) {
29 fprintf(stderr
, "Array index out of bounds %s:%d. Index: %d. Array size: %d\n", __FILE__
, __LINE__
, index
, array
->len
);
32 if (array
->len
== array
->maxlen
) {
33 myarray_enlarge(array
);
35 memmove(array
->elements
+ (index
+ 1) * array
->elsize
, array
->elements
+ index
* array
->elsize
, (array
->len
- index
)*array
->elsize
);
36 void *toinsert
= array
->elements
+ (index
* array
->elsize
);
37 memcpy(toinsert
, element
, array
->elsize
);
41 void myarray_insert_sorted_helper(MArray array
, void *element
, int left
, int right
) {
46 _myarray_insert(array
, element
, left
);
50 index
= (left
+ right
) / 2;
51 retVal
= array
->cmpfunc(element
, array
->elements
+ index
* array
->elsize
);
54 _myarray_insert(array
, element
, index
);
55 } else if (retVal
< 0) {
56 myarray_insert_sorted_helper(array
, element
, left
, index
- 1);
58 myarray_insert_sorted_helper(array
, element
, index
+ 1, right
);
62 void _myarray_insert_sorted(MArray array
, void *element
) {
63 if (array
->cmpfunc
== NULL
) {
64 _myarray_insert(array
, element
, array
->len
);
66 myarray_insert_sorted_helper(array
, element
, 0, array
->len
- 1);
70 void myarray_remove_index(MArray array
, int index
) {
71 memmove(array
->elements
+ index
* array
->elsize
, array
->elements
+ (index
+ 1) * array
->elsize
, (array
->len
- index
- 1)*array
->elsize
);
75 void myarray_free(MArray array
) {
76 free(array
->elements
);
80 void myarray_reset(MArray array
) {