#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;
}
以下几行:
//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
我收到以下错误消息:
dictionary.c:在函数'load'中:
分配
dictionary.c:112:29:错误:在非结构或联合的事物中请求成员'word' dictionary.c:135:32:错误:在非结构或联合的事物中请求成员'word' dictionary.c:138:10:错误:在非结构或联合的事物中请求成员'next' dictionary.c:139:31:错误:从不兼容的指针类型[-Werror]
问题是什么?
答案 0 :(得分:3)
非常简单:
node *n = malloc( sizeof(node) );
fscanf(dict, "%s", n.word);
n
是指向node
的指针,但n.word
表示n
本身是node
。对于指针,语法略有不同。
fscanf(dict, "%s", n->word);