Created
April 12, 2020 14:14
-
-
Save christianscott/47cb84bbed5f6ba7525b3608febb60fa to your computer and use it in GitHub Desktop.
c array helpers
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
#include <stdio.h> | |
#include <stdlib.h> | |
#define ARRAY_CAPACITY_INDEX 0 | |
#define ARRAY_LENGTH_INDEX 1 | |
#define ARRAY_DATA_START_INDEX 2 | |
#define capacity(array) array[ARRAY_CAPACITY_INDEX] | |
#define length(array) array[ARRAY_LENGTH_INDEX] | |
#define get(array, index) array[ARRAY_DATA_START_INDEX + index] | |
#define set(array, index, value) get(array, index) = value | |
static int *array_grow(int *array, int size) | |
{ | |
int desired_capacity = length(array) + size + 2; | |
if (desired_capacity > capacity(array)) { | |
int new_capacity = capacity(array); | |
while (desired_capacity > new_capacity) { | |
new_capacity = new_capacity * 2; | |
} | |
capacity(array) = new_capacity; | |
array = realloc(array, new_capacity * sizeof(int)); | |
} | |
return array; | |
} | |
void array_print(int *array) | |
{ | |
printf("length = %d, capacity = %d\n", length(array), capacity(array)); | |
printf("["); | |
for (int i = 0; i < length(array); i++) { | |
if (i == length(array) - 1) { | |
printf("%d", get(array, i)); | |
} else { | |
printf("%d, ", get(array, i)); | |
} | |
} | |
printf("]\n"); | |
} | |
int *array_new(int cap) | |
{ | |
if (cap < 2) { | |
cap = 2; | |
} | |
int *array = malloc(cap * sizeof(int)); | |
length(array) = 0; | |
capacity(array) = cap; | |
return array; | |
} | |
int *array_push(int *array, int value) | |
{ | |
int len = length(array); | |
array = array_grow(array, len + 1); | |
set(array, len, value); | |
length(array) = len + 1; | |
return array; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment