2
#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]
有什麼問題?
謝謝!但是,我如何解決這個問題呢?散列表[hash_value] =&n;給我的錯誤:從不兼容的指針類型分配 – hannah 2012-07-30 00:59:49
我不知道;我沒有在任何地方看到'hashtable'的聲明,所以我不知道它是什麼數據類型! – 2012-07-30 01:05:20
糟糕!讓我補充說明: struct node * hashtable [HASH_SIZE]; – hannah 2012-07-30 01:16:21