Skip to content

Instantly share code, notes, and snippets.

@tiffany352
Last active August 29, 2015 14:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tiffany352/7387a1bb4171d9d05939 to your computer and use it in GitHub Desktop.
Save tiffany352/7387a1bb4171d9d05939 to your computer and use it in GitHub Desktop.
struct thingvec {
thing *data;
size_t capacity, size;
};
void append(struct thingvec *self, thing t)
{
if (self->size >= self->capacity) { // there's no free slots left
size_t newcap = self->capacity * 2; // double in capacity, hits O(N) case every log(N) appends
size_t ts = sizeof(thing);
thing *tmp = malloc(ts * newcap); // allocate the new area of memory
memcpy(tmp, self->data, self->capacity * ts); // copy the old data into the new area of memory, this is the O(N) part
// you could just use realloc with glibc, but the C spec doesn't guarantee that realloc will keep the contents
// if the new size is larger than the old size, only if the new size is smaller or the same size.
free(self->data); // free the old area
self->data = tmp; // update the struct
self->capacity = newcap;
}
self->data[self->size++] = t; // insert the element right after the last element, and then increment the size by 1
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment