#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: 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]
有什么问题吗?
最佳答案
非常简单:
node *n = malloc( sizeof(node) );
fscanf(dict, "%s", n.word);
n
是指向 node
的指针,但 n.word
暗示 n
本身是一个 节点
。对于指针,语法有点不同。
fscanf(dict, "%s", n->word);
关于c - 不兼容的指针类型和结构问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11714160/