Skip to content

Instantly share code, notes, and snippets.

@pegvin
Created April 7, 2024 17:10
Show Gist options
  • Save pegvin/fa4f567d237b7d30e673f13e3ef23cab to your computer and use it in GitHub Desktop.
Save pegvin/fa4f567d237b7d30e673f13e3ef23cab to your computer and use it in GitHub Desktop.
Dynamic Array in C
#include "dynarr.h"
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
bool DynArr_Init(DynArr *arr, uint8_t itemSize, uint32_t capacity) {
arr->data = malloc(capacity * itemSize);
if (arr->data == NULL) return false;
arr->len = 0;
arr->cap = capacity;
arr->iSize = itemSize;
return true;
}
bool DynArr_Push(DynArr* arr, const void* value) {
if (arr->len >= arr->cap) {
arr->data = realloc(arr->data, arr->cap + 10 + (arr->cap - arr->len));
if (!arr->data) {
return false;
}
arr->cap += 10;
}
memcpy(arr->data + (arr->len * arr->iSize), value, arr->iSize);
arr->len++;
return true;
}
bool DynArr_Remove(DynArr* arr, uint32_t index) {
if (arr->len < 2) return false;
for (uint32_t i = index + 1; i < arr->len; i++) {
memcpy(arr->data + ((i - 1) * arr->iSize), arr->data + (i * arr->iSize), arr->iSize);
}
arr->len--;
return true;
}
void DynArr_Free(DynArr *arr) {
free(arr->data);
memset(arr, 0, sizeof(*arr));
}
#ifndef BRAINFUCK_DYNAMIC_ARRAY_H_INCLUDED_
#define BRAINFUCK_DYNAMIC_ARRAY_H_INCLUDED_ 1
#pragma once
#include <stdint.h>
#include <stdbool.h>
typedef struct {
void* data; // Items
uint32_t len; // Items currently holding
uint32_t cap; // Total Items can hold
uint8_t iSize; // Item Size
} DynArr;
bool DynArr_Init(DynArr* arr, uint8_t itemSize, uint32_t capacity);
bool DynArr_Push(DynArr* arr, const void* value);
bool DynArr_Remove(DynArr* arr, uint32_t index);
void DynArr_Free(DynArr* arr); // Doesn't Do Any NULL Checks
#endif // !BRAINFUCK_DYNAMIC_ARRAY_H_INCLUDED_
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment