Skip to content

Instantly share code, notes, and snippets.

@icholy
Last active December 28, 2015 19:09
Show Gist options
  • Save icholy/7548764 to your computer and use it in GitHub Desktop.
Save icholy/7548764 to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct Vector_t { int* arr; int sz; int cap; };
typedef struct Vector_t Vector;
Vector*
vector_new(int sz, int cap)
{
Vector* v = (Vector*)malloc(sizeof(Vector));
if (v == NULL)
{
return NULL;
}
v->sz = sz;
v->cap = cap;
v->arr = malloc(sizeof(int) * cap);
if (v->arr == NULL)
{
free(v);
return NULL;
}
return v;
}
int
vector_expand(Vector* v)
{
int new_cap = v->cap * 2;
int* new_arr = (int*)malloc(sizeof(int)*new_cap);
if (new_arr == NULL)
{
return -1;
}
memcpy(new_arr, v->arr, sizeof(int)*v->sz);
free(v->arr);
v->arr = new_arr;
v->cap = new_cap;
return 0;
}
void
vector_each(Vector* v, void (*fn)(int))
{
int sz = v->sz;
int* arr = v->arr;
for (int i = 0; i < sz; i++)
{
fn(arr[i]);
}
}
int
vector_free(Vector* v)
{
free(v->arr);
free(v);
return 0;
}
int
vector_append(Vector* v, int x)
{
if (v->sz == v->cap)
{
if (vector_expand(v) != 0)
{
return -1;
}
}
v->arr[v->sz++] = x;
return 0;
}
void
print_int(int x) { printf("%d\n", x); }
int
main(void) {
Vector* v = vector_new(0, 1);
if (v == NULL)
{
printf("could not allocate vector\n");
return 1;
}
for (int i = 0; i < 10; i++)
{
if (vector_append(v, i * 10) != 0)
{
printf("error appending");
return -1;
}
}
vector_each(v, &print_int);
printf("size: %d, capacity: %d\n", v->sz, v->cap);
if (vector_free(v) != 0)
{
printf("could not free vector");
return 1;
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment