123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152 |
- #include <stdlib.h>
- #include <stdio.h>
- #include "dd_dynamic_array.h"
- #include <string.h>
- int dd_da_init(struct dd_dynamic_array *da, int el_size) {
-
- da->element_size = el_size;
- da->elements = 0;
- da->array_size = 0;
- da->array = 0;
-
- return 0;
- }
- int dd_da_inita(struct dd_dynamic_array *da, int el_size, int ar_size) {
-
- da->element_size = el_size;
- da->elements = 0;
-
- da->array_size = ar_size;
- da->array = malloc( da->element_size *da->array_size );
-
- if (!da->array) {
- fprintf(stderr, "da_inita: cannot allocate memory\n");
- return -1;
- }
-
- return 0;
- }
- int dd_da_add(struct dd_dynamic_array *da, void *data) {
-
-
- if (!da->array) {
-
- da->array_size = 3;
- da->array = malloc(da->element_size *da->array_size);
-
- if (!da->array) {
- printf("da_add: cannot allocate memory\n");
- return -1;
- }
- } else
-
- if (da->elements +1 > da->array_size) {
-
- da->array_size *= 2;
- void *temp = realloc(da->array, da->element_size *da->array_size);
-
- if (temp) {
- da->array = temp;
- }
-
- else {
- printf("error: cannot re-allocate memory, abort\n");
- return -1;
- }
- }
-
- memcpy( ((char*)da->array) +(da->element_size *da->elements),
- data, da->element_size);
-
- da->elements++;
-
- return 0;
- }
- int dd_da_adda(struct dd_dynamic_array *da, void *data, unsigned int ar_size) {
-
- for (unsigned int i = 0; i < ar_size; i++) {
- if (dd_da_add(da, ((char*) data) +(da->element_size *i)) != 0) {
- fprintf(stderr, "da_adda: unable to add array of data to dynamic array\n");
- return -1;
- }
- }
- return 0;
- }
- int dd_da_pop(struct dd_dynamic_array *da) {
- if (da->elements > 0) {
- da->elements--;
- if (da->elements < da->array_size/3) {
- da->array_size /= 3;
- void *ptr;
- ptr = realloc(da->array, da->array_size * da->element_size);
- if (ptr) {
- da->array = ptr;
- return 0;
- }
- return -1;
- }
- return 0;
- }
- return -1;
- }
- int dd_da_remove(struct dd_dynamic_array *da, unsigned int element) {
-
- if (element >= da->elements) {
- return -1;;
- }
-
- unsigned int i = element;
- for (i = element+1; i < da->elements; i++) {
- memcpy( dd_da_get(da, i-1), dd_da_get(da, i), da->element_size );
- }
-
- da->elements--;
-
- return 0;
- }
- void dd_da_free(struct dd_dynamic_array *da) {
-
- if (da->array) {
- free(da->array);
- }
- }
- void *dd_da_get(struct dd_dynamic_array *da, unsigned int element) {
- return ((char*)da->array) +(element *da->element_size);
- }
|