Reputation: 909
#define HASH_SIZE 5
// prototype
int hash(char *word);
// counter
int counter;
// node
typedef struct node
{
char word[LENGTH + 1];
struct node *next;
} node;
// hash table
struct node *hashtable[HASH_SIZE];
bool
load(const char *dictionary)
{
// open the dictionary
FILE *dict = fopen(dictionary, "r");
if(dict == NULL)
{
printf("Could not open %s.\n", dictionary);
return false;
}
// set all values in the hash table to null
for(int i = 0; i < HASH_SIZE; i++)
{
hashtable[i] = NULL;
}
// set the counter to 0
counter = 0;
// iterate through the words in the dictionary
while (!feof(dict))
{
//declare a node
node *n = malloc( sizeof(node) );
// copy the word into the node
fscanf(dict, "%s", n.word);
// hash the word
int hash_value = hash(n.word);
// start saving addresses to the hashtable
n.next = hashtable[hash_value];
hashtable[hash_value] = &n;
// that's one more!
counter++;
}
fclose(dict);
return true;
}
For the following lines:
//declare a node
node *n = malloc( sizeof(node) );
// hash the word
int hash_value = hash(n.word);
// start saving addresses to the hashtable
n.next = hashtable[hash_value];
hashtable[hash_value] = &n;r code here
I receive the following error messages:
dictionary.c: In function 'load':
dictionary.c:112:29: error: request for member 'word' in something not a structure or union
dictionary.c:135:32: error: request for member 'word' in something not a structure or union
dictionary.c:138:10: error: request for member 'next' in something not a structure or union
dictionary.c:139:31: error: assignment from incompatible pointer type [-Werror]
What's the issue?
Upvotes: 2
Views: 1023
Reputation: 81684
Really simple:
node *n = malloc( sizeof(node) );
fscanf(dict, "%s", n.word);
n
is a pointer to a node
, but n.word
implies that n
itself is a node
. For a pointer, the syntax is a little different.
fscanf(dict, "%s", n->word);
Upvotes: 3