c - 指针和结构

标签 c pointers

#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "dictionary.h"

#define HASH_SIZE 100

// prototype
int hash(char *word);

// counter
int counter;

// node
typedef struct
{
    char *word;
    node *next;
} node;

// hash table
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))
    {
        // get word into a string
        char gotcha[LENGTH];
        fscanf(dict, "%s", gotcha);

        // declare a node and allocate memory
        node n;
        n.word = malloc( strlen(gotcha)*sizeof(char) );

        // save the word into the node
        strcpy(n.word, gotcha);

        // hash the word, baby!
        int hash_value = hash(n.word);

        // start saving addresses to the hashtable
        n.next = hashtable[hash_value];
        hashtable[hash_value] = &n;

        //test
        int len = strlen(n.word);
        printf("%s\n", n.word);
        printf("%i\n", len);

        // that's one more!
        counter++;
    }


    fclose(dict);

    return true;
}

我在这两行代码中收到以下两个错误:

    n.next = hashtable[hash_value];
    hashtable[hash_value] = &n;

dictionary.c:89:16: 错误:从不兼容的指针类型赋值 [-Werror] dictionary.c:90:31: 错误:从不兼容的指针类型赋值 [-Werror] 如何在这两个地方保存指针值?我对此很陌生,所以请记住这一点。 :)

最佳答案

在您的结构中,类型节点尚未定义。将其更改为使用结构标记:

typedef struct node
{
    char *word;
    struct node *next;
} node;

关于c - 指针和结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11698087/

相关文章:

编译器警告将结构数组(结构本身的成员)传递给函数

android - 文本到语音 - 空指针异常

c++ - 使用 argv[1] 作为文件名问题

c - C 中的 IEEE-754 浮点异常

c - 如果在待发送期间有传入数据包,packetbuf 如何在 ContikiOS 中工作?

将表转换为结构体

c - 将二维指针数组传递给函数给出错误

C++ 将指针传递给 vector 元素而不是数组指针

c++ - 将指针与 NULL 进行比较时程序崩溃

c - C中双向链表的内存问题