c - 不兼容的指针类型和结构问题

标签 c pointers

#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/

相关文章:

objective-c - 使用未解析的标识符 'PKCS7_type_is_signed'

c - 为什么我的程序显示数组地址而不是其内容?

.net - .net 中的固定 block

function - Golang - 为什么我可以从值类型调用指针接收器方法?

c - C-指向矩阵的指针

c - 线程在pthread_create之后立即执行?

c - 如何使用指针数组反转字符串?

c - 指向同一堆区域的随机地址的双指针

c - 嵌入式:大多数 CRT 启动代码不使用 memcpy/memset——为什么?

c - C 语言的输出是什么?