1
#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;
}

この 2 行のコードで、次の 2 つのエラーが表示されます。

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

Dictionary.c:89:16: エラー: 互換性のないポインター型からの割り当て [-Werror] dictionary.c:90:31: エラー: 互換性のないポインター型からの割り当て [-Werror] これら 2 つの場所にポインター値を保存するにはどうすればよいですか? 私はこれに慣れていないので、覚えておいてください。:)

4

3 に答える 3

2

あなたの構造では、型ノードはまだ定義されていません。構造タグを使用するように変更します。

typedef struct node
{
    char *word;
    struct node *next;
} node;
于 2012-07-28T04:20:42.773 に答える
0

構造体を定義する前に、構造体のtypedef名を定義します。これにより、順序を気にせずに構造体を相互に参照でき、一貫性のない定義を必要としません。構造体キーワードを使用する場合と使用しない場合があります。C ++では、typedef行を完全に削除できることに注意してください。

typedef struct node node;

struct node
{
    char* word;
    node* next;
};
于 2012-07-28T04:57:17.487 に答える
0

これ:

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

構文エラーです。node *next;型として作成する typedef の末尾の前に発生しますnode。何らかの理由でコンパイラがこれを受け入れた場合、おそらく「ノード」と呼ばれる 2 つの異なるタイプがあると考えられます。これは、それらの一方が他方と互換性がない理由を説明しています。その typedef の愚かさをあきらめて (構造体は一般に typedef されるべきではありません)、単に使用する必要があります

struct node
{
    char *word;
    struct node *next;
};
于 2012-07-28T04:22:16.180 に答える