Last active
August 29, 2015 14:02
-
-
Save tiffany352/7387a1bb4171d9d05939 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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