Skip to content

Instantly share code, notes, and snippets.

@qexat
Last active August 5, 2023 11:06
Show Gist options
  • Save qexat/aa0ea59b8d6356e988a00e0a45431241 to your computer and use it in GitHub Desktop.
Save qexat/aa0ea59b8d6356e988a00e0a45431241 to your computer and use it in GitHub Desktop.
learning c lol
/* Vec */
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#define LAST_OF(array, length) array[length-1]
size_t get_capacity(size_t length)
{
size_t capacity = 1;
while (capacity < length)
capacity *= 2;
return capacity;
}
typedef struct Vec
{
long long *ptr;
size_t length;
size_t capacity;
} Vec;
long long vec_get(Vec *self, size_t index)
{
if (index >= self->length)
{
// This is terrible error handling but I don't know how to do it properly lol
fprintf(stderr, "Error: vec_get: index %lu is out of bounds", index);
exit(-1);
}
return self->ptr[index];
}
_Bool vec_needs_growing(Vec *self)
{
return self->length + 1 >= self->capacity;
}
void vec_grow(Vec *self)
{
size_t new_length = self->length + 1;
size_t new_capacity = get_capacity(self->length);
long long *new_ptr = malloc(sizeof(long long) * new_capacity);
for (unsigned int i = 0; i < self->length; i++)
new_ptr[i] = self->ptr[i];
free(self->ptr);
self->ptr = new_ptr;
self->length = new_length;
self->capacity = new_capacity;
}
void vec_print(Vec *self)
{
printf("[");
for (unsigned int i = 0 ; i < self->length; i++)
{
if (i > 0)
printf(", ");
printf("%lld", self->ptr[i]);
}
printf("]\n");
}
void vec_append(Vec *self, long long value)
{
if (vec_needs_growing(self))
vec_grow(self);
else
self->length++;
LAST_OF(self->ptr, self->length) = value;
}
long long vec_pop(Vec *self)
{
long long value = LAST_OF(self->ptr, self->length);
self->length--;
return value;
}
Vec* vec_new(size_t argc, ...)
{
va_list argv;
va_start(argv, argc);
size_t capacity = get_capacity(argc);
Vec *v = malloc(sizeof(Vec));
v->ptr = malloc(sizeof(long long) * capacity);
v->length = argc;
v->capacity = capacity;
for (unsigned int i = 0; i < argc; i++)
v->ptr[i] = va_arg(argv, long long);
return v;
}
int main(void)
{
Vec *v = vec_new(3, 86, 41, 237);
printf("length: %lu, capacity: %lu\n", v->length, v->capacity);
vec_print(v);
printf("2nd element: %llu\n\n", vec_get(v, 1));
vec_append(v, 19);
printf("length: %lu, capacity: %lu\n", v->length, v->capacity);
vec_print(v);
printf("4th element: %llu\n\n", vec_get(v, 3));
vec_pop(v);
printf("length: %lu, capacity: %lu\n", v->length, v->capacity);
vec_print(v);
free(v);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment