I've been trying to fix this bug for the past couple of days, but it seems this one I really can't figure out on my own. Hope you guys can help a bit.
Here's the code for my load function in pset5.
#define HASH_SIZE 26
#define LENGTH 45
typedef struct node
{
char *word;
struct node *next;
}
node;
bool load(const char *dictionary){
The first part works: opening the file and creating an array of pointers for the hash table.
// Prepare hash table
node *head = NULL;
node *dict_table[HASH_SIZE];
FILE *dict_file = fopen(dictionary, "r");
if (!dict_file)
{
return false;
}
// Fill hash table with pointers
int i = 0;
while (i < HASH_SIZE)
{
dict_table[i] = head;
i++;
}
// Prepare variables
int index = 0;
char *dWord = malloc(sizeof(char) * LENGTH);
I then iterate through the dictionary while checking for '\n' to find the words.
// Prepare variables
int index = 0;
char dWord[LENGTH];
// Iterate over dictionary
for (char ch = fgetc(dict_file); ch != EOF; ch = fgetc(dict_file))
{
// Word not found yet
if (ch != '\n')
{
dWord[index] = ch;
index++;
}
// Word found!
else
{
dWord[index] = '\0';
// Allocate new node
node *new = malloc(sizeof(node));
if(new == NULL)
{
return 1;
}
// Assign value and point head to new node
new->word = dWord;
new->next = head;
head = new;
// Update variables
words++;
index = 0;
}
}
for (node *counter = head; counter != NULL; counter = counter->next)
{
printf("LIST: %s\n", counter->word);
}
return true;
}
}
The problem is that when I print the linked list at the end, the output equals n times the last word read from the dictionary. Somehow the list is not building correctly. I tried simplifying the code by getting rid of the for loop at the top and the conditions while only using a couple of words as input, which worked just fine.
I cannot figure out what goes wrong here! It must have something to do with the if conditions and the loop because the linked list stuff works on its own.
Thanks!
p.s. I'm not using the hash table array yet. Just trying to build a single linked list first.