源码如下:
#ifndef _DARR_H_
#define _DARR_H_
#include <stdint.h>
#include <stdlib.h>
#include <memory.h>
#define DARR_MALLOC malloc
#define DARR_FREE free
#define DEFAULT_DARR_SZ 128
struct darr_t {
uint16_t size;
uint16_t cusor;
void * __array[DEFAULT_DARR_SZ];
void ** array;
};
struct darr_t *darr_create() {
struct darr_t *darr = NULL;
darr = (struct darr_t *)DARR_MALLOC(sizeof(struct darr_t));
darr->array = darr->__array;
darr->size = DEFAULT_DARR_SZ;
darr->cusor = 0;
return darr;
}
int darr_append(struct darr_t *darr, void *e) {
void **array_tmp = NULL;
if (darr == NULL) {
return -1;
}
if (darr->cusor == darr->size) {
array_tmp = (void **)DARR_MALLOC(sizeof(void *) * 2 * darr->size);
memcpy(array_tmp, darr->array, sizeof(void *) * darr->size);
darr->size *= 2;
}
darr->array[darr->cusor ++] = e;
return 0;
}
void darr_destroy(struct darr_t *darr) {
if (darr == NULL) {
return;
}
if (darr->array != darr->__array) {
DARR_FREE(darr->array);
}
DARR_FREE(darr);
return;
}
#endif