//------------------------HashTable Class----------------------
class HashTable {
Node *nodeArray[size];
public:
/** this hash function returns an index to the array */
/* int hashFunction(string key) {
for (int i=1; i<key.length(); i++)
key += key[i];
return (key%size) ;
}
*/ /** put the value into the array using an index generated using hash function */
void put(string key)
{
int index = DJBHash(key) ;
cout << index;
nodeArray[index] = new Node(key);
// creates pointers that will be used to build the linked list
NodeType *current = NULL, *prev = NULL, *head = NULL ;
for (int i=0; i < 8; i++) { // iterates eight times
current = new NodeType ; // creates a new node
current->next = NULL ; // let next point nowhere
current->x = i ; // assign value to member variable
if (head == NULL) { // if this is the first node
head = current ; // let head point there
}
else { // if this is not the first node
prev->next = current ; // let prev node point to this one
}
prev = current ; // let prev becomes the current node
}
}
};
//--------------------------------HashTable class End----------------------
this is a class and the build breaks at this line: nodeArray[index] = new Node(key);
Visual studio shows this at run time:
Unhandled exception at 0x0041aead in MiniSearchEngineProj.exe: 0xC0000005: Access violation writing location 0xbf435d74.
Thanks for your reply. I think you are right. My index is sometimes negative number and also it is quite number. So let me elaborate on what I am trying to achieve. I am writing code to read in the words from text files and save them as strings (token). Then I am trying to feed in these words to a Hash function and trying to generate indices to store these tokens as keys in hash table. My hash function is shown below. I am not understanding why it is not giving me correct indices. it shoudl take string as input. Any idea whats wrng here. thanks.
1 2 3 4 5 6 7 8 9 10 11 12 13
unsignedint DJBHash(const std::string& str)
{
unsignedint hash = 5381;
for(std::size_t i = 0; i < str.length(); i++)
{
hash = ((hash << 5) + hash) + str[i];
}
return hash;
}
/* End Of DJB Hash Function */
first DJBHash() results an unsignedint you should stick to it when you call it (like that unsignedint index = DJBHash(key) ;) since you get a large number by shifting it 5 times for each char in your string (is this intended?) and that leads when converting to signed to a negative number.
Even sticking to unsigned doesn't help since your hash can easily exceed the maximum size of your array of 40000. You have to limit it accordingly.