Reputation: 533
I've been working 5 days straight on this program, and can't figure out why it's acting like this. Thanks for helping me out.
There is code in the file speller.c that calls 4 functions in the file dictionary.c
In speller.c, it calls a certain function:
bool misspelled = !check(word);
If misspelled is false, it means the check function returned true.
Here is the check function, in dictionary.c:
bool check(const char *word)
{
int key = hash(word);
printf("Word: %s position: %i\n", word, key);
node* trav = dictArray[key];
while (trav != NULL)
{
if(trav->word == word)
printf("%s found in the dictionary\n", word);
return true;
trav = trav->next;
}
printf("%s NOT found in the dictionary\n", word);
return false;
Check() will go check in a hash table if it can find the word passed as argument in a hash table, and prints each word and it's key. If it finds it, it prints a message and return true
. If not, prints a message saying so, and return false
.
The hash table is an array of 26 elements, each are a struct with 2 elements, one being a string, the other a pointer to the next struct (node) in the list.
Nodes are added to lists depending on the first letter of the word.
The problem is that I have tested every word that gets added to the array, and even when the word is not there, the function still returns true
.
In fact, it returns true
for every word passed as argument.
Now the really puzzling behavior is that check() has to print something to the screen, just before returning either true
or false
. Either ...found ...
or ... NOT found ...
.
Well it doesn't. But it still returns 'true', which confuses me.
Any help? Should I paste the whole code from both file?
Upvotes: 0
Views: 630
Reputation: 223972
Look closely:
while (trav != NULL)
{
if(trav->word == word)
printf("%s found in the dictionary\n", word);
return true;
trav = trav->next;
}
There are no curly braces around the if
block. So with proper indentation what you really have is:
while (trav != NULL)
{
if(trav->word == word)
printf("%s found in the dictionary\n", word);
return true;
trav = trav->next;
}
So you always return true on the first loop iteration.
Also, you don't want to use ==
to compare strings. What you end up doing is comparing the pointer values, which will almost always be not equal. Use strcmp
to compare strings instead.
The fixed code:
while (trav != NULL)
{
if(!strcmp(trav->word, word)) {
printf("%s found in the dictionary\n", word);
return true;
}
trav = trav->next;
}
Upvotes: 4
Reputation: 224944
This code block:
if(trav->word == word)
printf("%s found in the dictionary\n", word);
return true;
Doesn't do what you think it does - add {}
around everything you want to be included in the if
statement:
if(trav->word == word)
{
printf("%s found in the dictionary\n", word);
return true;
}
Otherwise that return true
happens every time (and as you saw, without necessarily printing).
Upvotes: 1