0

我试图在通用哈希表中动态分配指向通用链表的指针数组,其大小取决于用户输入。请让我给你看代码。

这是驱动程序,用户将输入他们希望哈希表的大小,这与哈希表中应该有多少链表直接相关。

int main(int argc, char **argv)
{   
int i;
int n;
int count;
unsigned int seed=0;

HashObjectPtr job;
HashTablePtr table;

if (argc < 2) {
    fprintf(stderr, "Usage: %s <table size> [<test size=table size * 10>]);
    exit(1);
}
n = atoi(argv[1]);
count = n;
if (argc >=  3) {
    count = atoi(argv[2]);
    count *= 10;
}
if (argc == 4) {
    seed = atoi(argv[3]);
}
char * firstInput = (char *)malloc(sizeof(char) * 
strlen("I'm a void star made at the beginning") + 1);
firstInput = strcpy (firstInput, "I'm a void star made at the beginning");
table = createHashTable(n, getKey, toString, freeHashObject, compare);

for (i=0; i<n; i++)
{
    job = createHashObject(firstInput);
    HashInsert(table, job);
}

runRandomTests(count, seed, n, table);

if (DEBUG > 0)
    PrintHash(table);
free(firstInput);
FreeHashTable(table);
exit(
}

这是结构。我定义了链表数组 ListPtr * table => linkedList ** table;

typedef struct HashTable HashTable;
typedef struct HashTable * HashTablePtr;

struct HashTable {
int tableSize;
int (*getKey)(void *);
char *  (*toString)(void *);
void (*freeHashObject)(void *);
Boolean (*compare)(void *, void *);
ListPtr * table;
};

HashTablePtr createHashTable(int size, int (*getKey)(void *), char *  (*toString)(void *), void (*freeHashObject)(void *), Boolean (compare)(void *, void *));
void HashInsert(HashTablePtr table, HashObjectPtr object);
HashObjectPtr HashSearch (HashTablePtr table, HashObjectPtr obj);
void PrintHash(HashTablePtr table);
void FreeHashTable(HashTablePtr table);
HashObjectPtr HashRemove(HashTablePtr table, HashObjectPtr obj);
int HashFunction(HashObjectPtr obj);

这是初始化链表的函数。

HashTablePtr createHashTable(int size, int (*getKey)(void *), char * (*toString)(void *), void (*freeHashObject)(void *), Boolean (*compare)(void *, void *))
{
HashTablePtr h = (HashTablePtr)malloc(sizeof(HashTable));
h -> tableSize = size;
h -> getKey = getKey;
h -> toString = toString;
h -> freeHashObject = freeHashObject;
h -> compare = compare;

h -> table = (ListPtr *)malloc(sizeof(ListPtr)*size);
int i;
for (i = 0; i < size; i++)
{
    h -> table[i] = createList(getKey, toString, freeHashObject);
}
}

这是创建链表的函数

ListPtr createList(int(*getKey)(void *), 
               char * (*toString)(void *),
               void (*freeHashObject)(void *))
{
ListPtr list;
list = (ListPtr) malloc(sizeof(List));
list->size = 0;
list->head = NULL;
list->tail = NULL;
list->getKey = getKey;
list->toString = toString;
list->freeObject = freeHashObject;
return list;
}

我在 Eclipse 的调试器中逐步完成了它,它编译和运行良好,但是当我在 CreateHashTable 函数期间单击 h 内的“表”变量时,一切看起来都很好,循环遍历并在每个索引处创建列表。但是当我去插入时,我得到了一个段错误。

它必须与我初始化 ListPointers 数组的方式有关,但我想不出更好的方法。

请帮忙?

谢谢

4

0 回答 0