Skip to content

Instantly share code, notes, and snippets.

@tungd
Created September 20, 2011 13:35
Show Gist options
  • Save tungd/1229073 to your computer and use it in GitHub Desktop.
Save tungd/1229073 to your computer and use it in GitHub Desktop.
Symbol table example
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define LEN 80
#define INIT_SIZE 30
typedef struct Entry {
void* key;
void* value;
} Entry;
typedef struct SymbolTable {
Entry* entries;
int size;
int total;
Entry (*make_entry)(void*, void*);
int (*compare)(void*, void*);
} SymbolTable;
SymbolTable create_symbol_table(Entry (*make_entry_fn)(void*, void*), int (*compare_fn)(void*, void*)) {
SymbolTable t;
t.entries = (Entry*) malloc(INIT_SIZE * sizeof(Entry));
t.total = 0;
t.size = INIT_SIZE;
t.make_entry = make_entry_fn;
t.compare = compare_fn;
return t;
}
void drop_symbol_table(SymbolTable* t) {
free(t->entries);
}
void add_entry(void* key, void* value, SymbolTable* t) {
if (t->total == t->size) {
t->size += INIT_SIZE;
t->entries = (Entry*) realloc(t->entries, t->size * sizeof(Entry));
}
t->entries[ t->total ] = t->make_entry(key, value);
t->total += 1;
}
Entry make_phone(void* name, void* phone) {
Entry res;
res.key = strdup( (char*)name );
res.value = malloc(sizeof(long));
memcpy( res.value, phone, sizeof(long) );
return res;
}
int get_entry(void* key, SymbolTable t) {
int i;
for (i = 0; i < t.total; i += 1) {
if (t.compare(key, &t.entries[i]) == 0) return i;
}
return -1;
}
int compare_phone(void* m, void* n) {
return strcmp((char*) m, (char*) n);
}
void print_phone(Entry e) {
printf("Name: %s, Phone num: %ld\n", (char*) e.key, *((long*) e.value));
}
int main() {
int i;
SymbolTable p = create_symbol_table(make_phone, compare_phone);
long num = 123456789;
for (i = 0; i < 1000; i += 1) {
add_entry("Tung", &num, &p);
}
for (i = 0; i < 1000; i += 1) {
printf("%d: ", i);
print_phone(p.entries[0]);
}
drop_symbol_table(&p);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment