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:在函数'load'中:
dictionary.c:112:29:错误:请求成员'word'不是结构或联合
dictionary.c:135:32:错误:请求成员'word'在不是结构或联合
字典的东西。c:138:10:错误:在不是结构或联合字典的东西中请求成员“下一个”
。c:139:31:错误:来自不兼容的指针类型的赋值[-Werror]

有什么问题?

4

1 回答 1

3

真的很简单:

node *n = malloc( sizeof(node) );
fscanf(dict, "%s", n.word);

n是指向 a 的指针node,但n.word暗示它n本身是 a node。对于指针,语法略有不同。

fscanf(dict, "%s", n->word);
于 2012-07-30T00:34:56.880 回答