Reputation: 101
I am new to C and am currently writing a spell checker. To do this I am first loading a dictionary of words into a hash table for easy referencing. Here is my code:
bool load(const char* dictionary)
{
typedef struct node
{
char word[LENGTH + 1];
struct node* next;
}
node;
node* table[500];
FILE *fp;
fp = fopen("dictionaries/small", "r");
if(fp == NULL)
{
return 0;
}
node* new_node = malloc(sizeof(node));
fscanf(fp, "%s", new_node->word);
int hashed_word = hash_function(new_node->word);
if(table[hashed_word] == NULL) //if the table has no value at the index
{
table[hashed_word]->word = new_node->word; //Issue here
}
return 0;
}
This code very simply reads the first line (word) of a file and then hashes it (the first word 'cat' gives a hash of 2). I then check that the table dosen't have a word at the index the hash function gives.
I then want to start a linked list with the first link being the first word ('cat') and I'd build it from there. However when I run this code I get a problem here:
table[hashed_word]->word = new_node->word; //Issue here
and get this error:
dictionary.c:66:34: error: array type 'char [46]' is not assignable
table[hashed_word]->word = new_node->word;
~~~~~~~~~~~~~~~~~~~~~~~~ ^
1 error generated.
I thought this line would assign the 'word' part of table to be 'cat' (the word part of new_node) but it doesn't
Would someone please be able to tell me what I'm doing wrong? I imagine it's quite fundamental as pointers are confusing! I've been stuck on this for several days and am starting to get a bit disheartened so would love any help which could be offered.
Upvotes: 2
Views: 106
Reputation: 126536
You're creating a table of 500 pointers, but you're not initializing it to anything. You then go and check elements to see if they are null, which they might or might not be (they are just garbage).
When you try to add a word, you try to write it into a node already in a table, rather than just linking the newly allocated node into the table.
Your table is also a local variable, so will be inaccessable after the load
function returns.
The easiest fix for all of the above is to make your table and struct node
definition global:
typedef struct node
{
char word[LENGTH + 1];
struct node* next;
} node;
node *table[500] = { 0 };
and then use a loop to fill in the table;
bool load(const char* dictionary)
{
char word[256];
FILE *fp = fopen("dictionaries/small", "r");
if(fp == NULL)
return false;
while (fscanf(fp, "%255s", word) == 1) {
if (strlen(word) > LENGTH)
continue; // ignore words that are too long
int hashed_word = hash_function(word);
node* new_node = malloc(sizeof(node));
strcpy(new_node->word, word);
new_node->next = table[hashed_word];
table[hashed_word] = new_node;
}
fclose(fp);
return true;
}
Upvotes: 3