【问题标题】:Incompatible pointer type and struct issues不兼容的指针类型和结构问题
【发布时间】:2012-07-30 00:29:39
【问题描述】:
#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:在函数“加载”中:
dictionary.c:112:29:错误:请求成员“单词”不是结构或联合
dictionary.c:135:32:错误:请求成员“单词”不是结构或联合
dictionary.c:138:10:错误:请求成员“下一个”不是结构或联合
dictionary.c:139:31:错误:来自不兼容指针类型的赋值 [-Werror]

有什么问题?

【问题讨论】:

    标签: c pointers


    【解决方案1】:

    真的很简单:

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

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

    fscanf(dict, "%s", n->word);
    

    【讨论】:

    • 谢谢!不过,我该如何解决这个问题?哈希表[hash_value] = &n;给我错误:不兼容的指针类型的赋值
    • 我不知道;我在任何地方都没有看到hashtable的声明,所以我不知道它是什么数据类型!
    • 糟糕!让我将其添加到: struct node *hashtable[HASH_SIZE];
    • 啊,我明白了!我应该输入: hashtable[hash_value] = n;因为,正如你所说,n 是一个指针,而不是一个节点。无论如何,感谢您的帮助!
    猜你喜欢
    • 1970-01-01
    • 2012-04-22
    • 1970-01-01
    • 1970-01-01
    • 2014-12-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多