Skip to content

Instantly share code, notes, and snippets.

@tttardigrado
Created May 28, 2023 19:58
Show Gist options
  • Save tttardigrado/8610db9cd0cb7abfef7b8f61983f978a to your computer and use it in GitHub Desktop.
Save tttardigrado/8610db9cd0cb7abfef7b8f61983f978a to your computer and use it in GitHub Desktop.
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
struct vec {
size_t size, cpcty;
int *arr;
};
typedef struct vec Vec;
Vec *vec_new(size_t size) {
Vec *v = (Vec *)malloc(sizeof(Vec));
v->size = size;
v->cpcty = size;
v->arr = (int *)calloc(size, sizeof(int));
return v;
}
void vec_print(Vec *v) {
for (size_t i = 0; i < v->size; i++)
printf("%d ", v->arr[i]);
printf("(size: %lu, capacity: %lu)\n", v->size, v->cpcty);
}
Vec *vec_from_array(int arr[], size_t size) {
Vec *v = vec_new(size);
for (size_t i = 0; i < size; i++)
v->arr[i] = arr[i];
return v;
}
void vec_add(Vec *v, int val) {
if (v->size == v->cpcty) {
v->cpcty *= 2;
v->arr = realloc(v->arr, sizeof(int) * v->cpcty);
}
v->arr[v->size++] = val;
}
int vec_find(Vec *v, int val) {
for (size_t i = 0; i < v->size; i++)
if (v->arr[i] == val)
return i;
return -1;
}
int vec_at(Vec *v, size_t index) { return v->arr[index]; }
void vec_free(Vec *v) {
free(v->arr);
free(v);
}
int main() {
int arr[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
Vec *v = vec_from_array(arr, 11);
vec_print(v);
vec_add(v, 20);
vec_add(v, 30);
vec_print(v);
printf("%d - %d - %d\n", vec_at(v, 3), vec_find(v, 40), vec_find(v, 10));
vec_free(v);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment