Skip to content

Instantly share code, notes, and snippets.

@exelotl
Created December 30, 2013 00:35
Show Gist options
  • Save exelotl/8176467 to your computer and use it in GitHub Desktop.
Save exelotl/8176467 to your computer and use it in GitHub Desktop.
Simple self-resizing list of void pointers
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
typedef struct {
int capacity;
int size;
void** data;
} list_t;
list_t* list_create();
void list_free(list_t* self);
void list_push(list_t* self, void* item);
void* list_pop(list_t* self);
void* list_get(list_t* self, int pos);
void list_set(list_t* self, int pos, void* item);
list_t* list_create() {
list_t* self = malloc(sizeof(list_t));
self->capacity = 10;
self->size = 0;
self->data = malloc(self->capacity * sizeof(void*));
return self;
}
void list_free(list_t* self) {
free(self->data);
free(self);
}
void list_push(list_t* self, void* item) {
if (self->size >= self->capacity) {
self->capacity += 10;
self->data = realloc(self->data, self->capacity * sizeof(void*));
printf("Resized list (capacity = %d)\n", self->capacity);
}
self->data[self->size++] = item;
}
void* list_pop(list_t* self) {
if (self->size == 0)
return NULL;
return self->data[--self->size];
}
void* list_get(list_t* self, int pos) {
if (pos < 0 || pos >= self->size)
return NULL;
return self->data[pos];
}
void list_set(list_t* self, int pos, void* item) {
if (pos < 0) return;
if (pos >= self->size) {
int num_blocks = pos/10 + 1;
self->capacity = num_blocks*10;
self->data = realloc(self->data, self->capacity * sizeof(void*));
for (int i=self->size; i<self->capacity; i++)
self->data[pos] = NULL;
self->size = pos + 1;
}
self->data[pos] = item;
}
point_t* point_create(int x, int y) {
point_t* p = malloc(sizeof(point_t));
p->x = x;
p->y = y;
return p;
}
void point_free(point_t* p) {
free(p);
}
void point_print(point_t* p) {
if (p) printf("(%d, %d)\n", p->x, p->y);
else printf("(null)\n");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment