初始化结构的双指针

时间:2013-04-20 22:05:05

标签: c hash struct doubly-linked-list double-pointer

我试图在通用散列表中有一个指向通用链表的指针数组,动态分配,其大小取决于用户输入。请让我告诉你代码。

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

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 =&gt; 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中的“table”变量时,一切看起来都很好,循环遍历并在每个索引处创建列表。但是当我去插入时,我会遇到一个段错误。

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

请帮忙吗?

谢谢

0 个答案:

没有答案