0

このコード ブロックは、辞書ファイルを読み取り、それをハッシュ配列に格納します。このハッシュ配列は、リンクされたリストの競合解決を使用します。しかし、どういうわけか、途中で読みが止まってしまいます。(リンクされたリストが作成されたときに何らかの問題が発生すると想定しています。) データが空のハッシュ配列要素に格納されている場合、すべて正常に機能します。

#define SIZE_OF_ARRAY 350
typedef struct {
    char* key;
    int status; // (+1) filled, (-1) deleted, 0 empty
    LIST* list;
}HASHED_ARRAY;
void insertDictionary (HASHED_ARRAY hashed_array[])
{
    //Local Declaration
    FILE* data;
    char word[30];
    char* pWord;
    int index;
    int length;
    int countWord = 0;

    //Statement
    if (!(data = fopen("dictionaryWords.txt", "r")))
    {
        printf("Error Opening File");
        exit(1);
    }

    SetStatusToNew (hashed_array); //initialize all status to 'empty'

    while(fscanf(data, "%s\n", word) != EOF)
    {

        length = strlen(word) + 1;
        index = hashing_function(word);

        if (hashed_array[index].status == 0)//empty
        {
            hashed_array[index].key = (char*) malloc(length * sizeof(char));//allocate word.
            if(!hashed_array[index].key)//check error
            {
                printf("\nMemory Leak\n");
                exit(1);
            }
            strcpy(hashed_array[index].key, word); //insert the data into hashed array.
            hashed_array[index].status = 1;//change hashed array node to filled.
        }

        else
        {
            //collision resolution (linked list)
            pWord = (char*) malloc(length * sizeof(char));
            strcpy (pWord, word);

            if (hashed_array[index].list == NULL) // <====== program doesn't enter
                                            //this if statement although the list is NULL. 
                                //So I'm assuming this is where the program stops reading.
            {
                hashed_array[index].list = createList(compare); 
            }
            addNode(hashed_array[index].list, pWord); 
        }
        countWord++;
        //memory allocation for key
    }
    printStatLinkedList(hashed_array, countWord);
    fclose(data);
    return;
}

createListaddNode両方とも ADT 関数です。前者は関数ポインタ(compare関数内に私が作成したmain関数です)をパラメータとして取り、後者はリスト名とvoid型データをパラメータとして取ります。compareリンクされたリストを並べ替えます。問題を見つけてください。

4

1 に答える 1

1

hashed_arrayこの関数に渡す宣言の場所によっては、その内容が初期化されない場合があります。これは、すべてのエントリのすべての内容がランダムであることを意味します。これにはlistポインターが含まれます。

最初にこの配列を適切に初期化する必要があります。最も簡単な方法は、単純に使用することmemsetです。

memset(hashed_array, 0, sizeof(HASHED_ARRAY) * whatever_size_it_is);

これにより、すべてのメンバーがゼロに設定されます。つまりNULL、ポインターの場合です。

于 2013-05-02T06:03:40.103 に答える