Associative arrays/Creation/C: Difference between revisions

→‎From Scratch: include headers, use hash_t instead of Hash as struct name
(→‎From Scratch: remove hash_free function)
(→‎From Scratch: include headers, use hash_t instead of Hash as struct name)
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:
 
<lang c>typedef#include struct {<stdio.h>
#include <stdlib.h>
 
typedef struct {
int size;
void **keys;
void **values;
} Hashhash_t;
 
Hashhash_t *hash_new (int size) {
Hashhash_t *hashh = calloc(1, sizeof (Hashhash_t));
hashh->sizekeys = calloc(size, sizeof (void *));
hashh->keysvalues = calloc(size, sizeof (void *));
hashh->valuessize = calloc(size, sizeof (void *));
return hashh;
}
 
int hash_index (Hashhash_t *hashh, void *key) {
int indexi = (int) key % hashh->size;
while (hashh->keys[indexi] && hashh->keys[indexi] != key)
indexi = (indexi + 1) % hashh->size;
return indexi;
}
 
void hash_insert (Hashhash_t *hashh, void *key, void *value) {
int indexi = hash_index(hashh, key);
hashh->keys[indexi] = key;
hashh->values[indexi] = value;
}
 
void *hash_lookup (Hashhash_t *hashh, void *key) {
int indexi = hash_index(hashh, key);
return hashh->values[indexi];
}
 
int main () {
Hashhash_t *hashh = hash_new(15);
hash_insert(hashh, "hello", "world");
hash_insert(hashh, "a", "b");
printf("hello => %s\n", hash_lookup(hashh, "hello"));
printf("herp => %s\n", hash_lookup(hashh, "herp"));
printf("a => %s\n", hash_lookup(hashh, "a"));
return 0;
}</lang>
Anonymous user