Hello again,
I started writing a few lines of code and caught myself think 'Wow, hash tables are pretty nice, easy to write (havn't attacked index collision yet though.) and generally very cool stuff.' I hit a small snag though. First here's the code:
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
class hashTable {
protected:
char **table;
int keys;
//int **keysTable;
unsigned int GenerateHash(char *string);
public:
hashTable() {
keys = 0;
}
int Insert(char *key, char *value);
char *operator[] (char *);
};
char *hashTable::operator[] (char *key) {
return table[GenerateHash(key)];
}
int hashTable::Insert(char *key, char *value) {
int strSize = strlen(value);
unsigned int hash = GenerateHash(key);
table[hash] = (char *)malloc(sizeof(char) * strSize);
strcpy(table[hash], value);
//keysTable[keys] = (int *)malloc(sizeof(int));
//*keysTable[keys] = hash;
keys++;
return hash;
}
unsigned int hashTable::GenerateHash(char *key) {
unsigned int hash = 0;
int size = strlen(key);
for (int i = 1; i < size; i++) {
hash += (key[i] % 251) * i;
}
return hash;
}
int main() {
hashTable table;
int hash = table.Insert("key", "testing");
printf("%s:%i = %s\n", "key", hash, table["key"]);
return 0;
}
As soon as I uncomment 'int **keysTable' the program segfaults when I try to run it. If I uncomment that line and comment the 'int keys' line instead it dosn't segfault (uncommenting/commenting lines that depent on the variable).
And I can't for the life of me figure out where the problem lies.