1

Initially i had no problems implementing my hash table during the load function.

however when it came time to check for errors, i couldn't access my hash table in order to traverse my linked list.

I have since realised that this is because my hash table was placed on the stack and destroyed once the load function was exited.

The problem now is that when i go back and try to malloc myself a structure for the hash table i come up against errors.

A code snippet (simply showing the process of assigning all node pointers to point an initial value of zero) has been pasted to depict the problem.

//hash table

node* hTable = malloc(26*sizeof(node));
for(int n = 0; n<26; n++)
{
    *(hTable+n) = NULL;
}

the initial code is shown below and allows me to traverse and append the linked list but does not persist after the function execution. what am i doing wrong.

//hash table

node* hTable[26];
for(int n = 0; n<26; n++)
{
    hTable[n] = NULL;
}
1

That's because you declared your array inside your load function which makes it a local to it — it goes out of scope as the function returns.

Even if you allocated memory for your array on the heap (which I think of as not the best solution), you'll lose reference to it if it's declared inside your function — the memory will still be allocated, but you have no way to access it because you lose the way you access it with as the function terminates.

Same thing happens when you allocate memory for some pointer p then set p to NULL (you lose access to the memory you allocated because you're overwriting the address that's stored in that pointer and you have no way to get it back unless you have another pointer that stores it).

A good solution is to declare an array of nodes as a global variable.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .