Skip to content

Instantly share code, notes, and snippets.

@byBretema
Created February 28, 2024 16:30
Show Gist options
  • Save byBretema/0f193cd21fe03e6b517a2ee54dc32bb2 to your computer and use it in GitHub Desktop.
Save byBretema/0f193cd21fe03e6b517a2ee54dc32bb2 to your computer and use it in GitHub Desktop.
Dynamic Array in C (WIP)
#include <stdio.h>
#include <stdlib.h>
typedef struct {
int *array;
size_t size;
size_t capacity;
} darray;
void *safe_malloc(size_t size) {
void *ptr = malloc(size);
if (ptr == NULL) {
perror("Memory allocation failed");
exit(EXIT_FAILURE);
}
return ptr;
}
void *safe_realloc(void *ptr, size_t size) {
void *new_ptr = realloc(ptr, size);
if (new_ptr == NULL) {
perror("Memory reallocation failed");
exit(EXIT_FAILURE);
}
return new_ptr;
}
void darray_make(darray *arr) {
arr->array = (int *)safe_malloc(10 * sizeof(int));
arr->size = 0;
arr->capacity = 10;
}
void __darray_resize(darray *arr) {
arr->capacity *= 2;
arr->array = (int *)safe_realloc(arr->array, arr->capacity * sizeof(int));
}
void darray_add(darray *arr, int element) {
if (arr->size >= arr->capacity) {
__darray_resize(arr);
}
arr->array[arr->size++] = element;
}
void darray_remove_at(darray *arr, size_t index) {
if (index >= arr->size) {
//printf("Index out of bounds\n");
return;
}
#if 1
arr->array[i] = arr->array[arr->size-1]; // Just move the last element to this possition
#else
for (size_t i = index; i < arr->size - 1; ++i) {
arr->array[i] = arr->array[i + 1];
}
#endif
arr->size--;
}
void darray_copy(darray *dst, const darray *src) {
dst->size = src->size;
dst->capacity = src->capacity;
dst->array = (int *)safe_malloc(src->capacity * sizeof(int));
for (size_t i = 0; i < src->size; ++i) {
dst->array[i] = src->array[i];
}
}
void darray_delete(darray *arr) {
free(arr->array);
}
int main() {
darray darr;
darray_make(&darr);
// Example usage: appending integers
for (int i = 0; i < 20; ++i) {
darray_add(&darr, i);
}
// Printing the elements
for (size_t i = 0; i < darr.size; ++i) {
printf("%d ", darr.array[i]);
}
printf("\n");
// Creating a copy of darr
darray darr_copy;
darray_copy(&darr_copy, &darr);
// Printing the elements of the copy
printf("Copy of darr: ");
for (size_t i = 0; i < darr_copy.size; ++i) {
printf("%d ", darr_copy.array[i]);
}
printf("\n");
// Freeing memory
darray_delete(&darr);
darray_delete(&darr_copy);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment