Last active
August 9, 2021 02:46
-
-
Save ghoomfrog/e6744950455ca4c4a510ea7592138759 to your computer and use it in GitHub Desktop.
Dynamic Array Facilities
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#ifndef DARRAY_H | |
#define DARRAY_H | |
#define DARRAY_INITIAL_CAPACITY 64 | |
#include <stdlib.h> | |
#include <string.h> | |
typedef struct darray_t { | |
size_t length, capacity; | |
void **elements; | |
} darray_t; | |
void *dalloc() { | |
darray_t *a = malloc(sizeof(darray_t)); | |
if (!a) return 0; | |
a->length = 0; | |
a->capacity = DARRAY_INITIAL_CAPACITY; | |
if (!(a->elements = calloc(DARRAY_INITIAL_CAPACITY, sizeof(void*)))) { | |
free(a); | |
return 0; | |
} | |
return a; | |
} | |
void dfree(darray_t *a) { | |
free(a->elements); | |
free(a); | |
} | |
void *dget(darray_t *a, size_t i) { | |
return a->elements[i]; | |
} | |
void *dpush(darray_t *a, void *v) { | |
if (a->length >= a->capacity) { | |
size_t new_capacity = a->capacity * 2; | |
if (!(a->elements = realloc(a->elements, new_capacity * sizeof(void*)))) | |
return 0; | |
memset(a->elements + a->capacity, 0, a->capacity); | |
a->capacity = new_capacity; | |
} | |
return a->elements[a->length++] = v; | |
} | |
void *dpop(darray_t *a) { | |
return a->elements[--(a->length)]; | |
} | |
#define dset(a, i, v) ((a)->elements[i] = (void*)(v)) | |
#define dpush(a, v) (dpush((a), (void*)(long)(v))) | |
#endif |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment