Associative arrays/Creation/C: Difference between revisions

Content added Content deleted
(→‎From Scratch: remove hash_free function)
(→‎From Scratch: include headers, use hash_t instead of Hash as struct name)
Line 7: Line 7:
A hash table can be implemented with the following. Because of this example's simplicity, it comes with some restrictions on use and capabilities: It can't be resized automatically, if you try to insert more values than its capacity it will freeze, the hashing function is very simple, etc. All are fixable with additional logic or using a library:
A hash table can be implemented with the following. Because of this example's simplicity, it comes with some restrictions on use and capabilities: It can't be resized automatically, if you try to insert more values than its capacity it will freeze, the hashing function is very simple, etc. All are fixable with additional logic or using a library:


<lang c>typedef struct {
<lang c>#include <stdio.h>
#include <stdlib.h>

typedef struct {
int size;
int size;
void **keys;
void **keys;
void **values;
void **values;
} Hash;
} hash_t;


Hash *hash_new (int size) {
hash_t *hash_new (int size) {
Hash *hash = calloc(1, sizeof (Hash));
hash_t *h = calloc(1, sizeof (hash_t));
hash->size = size;
h->keys = calloc(size, sizeof (void *));
hash->keys = calloc(size, sizeof (void *));
h->values = calloc(size, sizeof (void *));
hash->values = calloc(size, sizeof (void *));
h->size = size;
return hash;
return h;
}
}


int hash_index (Hash *hash, void *key) {
int hash_index (hash_t *h, void *key) {
int index = (int) key % hash->size;
int i = (int) key % h->size;
while (hash->keys[index] && hash->keys[index] != key)
while (h->keys[i] && h->keys[i] != key)
index = (index + 1) % hash->size;
i = (i + 1) % h->size;
return index;
return i;
}
}


void hash_insert (Hash *hash, void *key, void *value) {
void hash_insert (hash_t *h, void *key, void *value) {
int index = hash_index(hash, key);
int i = hash_index(h, key);
hash->keys[index] = key;
h->keys[i] = key;
hash->values[index] = value;
h->values[i] = value;
}
}


void *hash_lookup (Hash *hash, void *key) {
void *hash_lookup (hash_t *h, void *key) {
int index = hash_index(hash, key);
int i = hash_index(h, key);
return hash->values[index];
return h->values[i];
}
}


int main () {
int main () {
Hash *hash = hash_new(15);
hash_t *h = hash_new(15);
hash_insert(hash, "hello", "world");
hash_insert(h, "hello", "world");
hash_insert(hash, "a", "b");
hash_insert(h, "a", "b");
printf("hello => %s\n", hash_lookup(hash, "hello"));
printf("hello => %s\n", hash_lookup(h, "hello"));
printf("herp => %s\n", hash_lookup(hash, "herp"));
printf("herp => %s\n", hash_lookup(h, "herp"));
printf("a => %s\n", hash_lookup(hash, "a"));
printf("a => %s\n", hash_lookup(h, "a"));
return 0;
return 0;
}</lang>
}</lang>