此代码块读取字典文件并将其存储在散列数组中。此散列数组使用链接列表冲突解决方案。但是,由于一些不可理解的原因,阅读在中间停止。 (我假设在制作链表时会出现问题。)当数据存储在空的散列数组元素中时,一切正常。
#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;
}
createList
和addNode
都是ADT功能。前者采用函数指针(compare
是我在main
函数内构建的函数)作为参数,后者采用列表名称,void类型数据作为参数。 compare
对链接列表进行排序。请发现我的问题。
答案 0 :(得分:1)
根据您声明传递给此函数的hashed_array
的位置,可能无法初始化它的内容。这意味着所有条目的所有内容都是随机的。这包括list
指针。
您需要先正确初始化此数组。最简单的方法是简单使用memset
:
memset(hashed_array, 0, sizeof(HASHED_ARRAY) * whatever_size_it_is);
这会将所有成员设置为零,即NULL
指针。