【问题标题】:Hashed array linked list collision resolution error散列数组链表冲突解决错误
【发布时间】:2013-04-26 05:15:03
【问题描述】:

此代码块读取字典文件并将其存储在散列数组中。这个散列数组使用链表冲突解决。但是,由于某种难以理解的原因,阅读在中间停止了。 (我假设在创建链表时会出现一些问题。)当数据存储在空的散列数组元素中时,一切正常。

#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 对链表进行排序。请找出我的问题。

【问题讨论】:

  • 阅读时总是停在同一个地方吗?您是否尝试过隔离所涉及的输入?您是否尝试过在调试器中单步执行代码以查看会发生什么?
  • 它在任何单词碰巧与前一个单词具有相同索引时停止,然后它通过第一个 else 语句。而且我不确定如何使用调试器。但是您可以在这里发现任何明显的错误吗?

标签: c data-structures hash hash-collision


【解决方案1】:

根据你在哪里声明你传递给这个函数的hashed_array,它的内容可能没有被初始化。这意味着所有条目的所有内容都是随机的。这包括list 指针。

您需要先正确初始化此数组。最简单的方法就是简单的使用memset

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

这会将所有成员设置为零,即NULL 用于指针。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-02-06
    • 1970-01-01
    • 1970-01-01
    • 2017-03-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-06
    相关资源
    最近更新 更多