【发布时间】:2022-01-25 04:29:45
【问题描述】:
内存异常在向哈希表中插入值时,我需要构建一个将值插入到哈希表中的函数,但存在内存问题,因为链向我抛出了异常 我想要一个解决方案
哈希表.h
struct HashTableElement
{
int key;
LinkedList* chain;
};
typedef struct HashTable HashTable;
struct HashTable
{
HashTableElement* hashTable;
int hashFunction;
int tableSize;
int cellsTaken;
int numOfElements;
};
链表.h
typedef struct LinkedList LinkedList;
struct LinkedList {
char* data;
LinkedList* next;
};
哈希表.c
HashTable* initTable(int tableSize, int hashFunction)
{
HashTable* table = (HashTable*)malloc(sizeof(HashTable));
table->tableSize = tableSize;
table->hashFunction = hashFunction;
if (table == NULL || tableSize < 1)
{
printf("EROR with malloc in initTable.");
exit(1);
}
table->hashTable = malloc(sizeof(HashTableElement) * tableSize);
int i;
for (i = 0; i < hashFunction; i++) {
table->hashTable[i].key = NULL;
table->hashTable[i].chain = NULL;
}
return table;
}
int insert(HashTable* ht, char* str)
{
HashTable* temp;
int h = hash(str, ht);
int i = 0;
while (ht->hashTable[h].key != 0 && (i < ht->tableSize)) {
if (ht->hashTable[h].key == *str) {
ht->hashTable[h].key = *str;
return; /* break is intended to quit the loop, but actually we want to exit the function altogether */
}
h = (h + 1) % ht->tableSize; /* changed 11 to the size specified */
i++; /* advance the loop index */
}
if (ht->hashTable[h].key == 0) {
ht->hashTable[h].chain->data = *str;
return 1;
}
return 0;
}
ht->hashTable[h].chain->data = *str; 中插入函数的问题 我该如何解决那里的异常?
【问题讨论】:
-
你应该检查
if (table == NULL...之前table->。 -
奇怪的是你
table->hashtable = malloc(...和tablesize,但随后使用for (i = 0; i < hashFunction; i++) ...中的hashfunction值循环其元素你的数组的边界。在那里循环tablesize更有意义。 -
您确定您的
hash函数将返回一个在您的hashtable范围内的h值吗?没问题,但ht->hashTable[h].key = *str;没用,因为您只是在上面的行中检查了它们是否相等。