【问题标题】:Hash table init_hash in cc中的哈希表init_hash
【发布时间】:2017-05-31 19:41:02
【问题描述】:

我需要用我得到的大小来初始化哈希表,我这里有问题t->arr_table[i]->key = NULL;

#include <stdio.h>

typedef struct element{
    char * key;      
    char * value;    
}element;

typedef struct HashTable{
    int size;    // size of the arr
    element **arr_table;   //arr of elements
}HashTable;


void init_hash(int size, HashTable * t)
{
    if (size < 1)
        return;
    t->size = size;
    t->arr_table = (element **)malloc(sizeof(element*)*size);
    if (t->arr_table == NULL) // out memory
        return;
    int i;
    for (i = 0; i < size; i++)
    { // initial list
        t->arr_table[i]->key = NULL;
        t->arr_table[i]->value = NULL;
    }

}



void main()
{
    HashTable *ht = (HashTable*)malloc(1*sizeof(HashTable));
    int size_ht = 9;
    init_hash(size_ht, ht);
    printf("...\n");
    return;
}

【问题讨论】:

  • “我有问题”。你不认为告诉我们问题到底是什么有意义吗?这不是常识吗?
  • 因为我不知道为什么会这样@kaylum
  • 您是在尝试创建一个指向元素的指针数组还是一个元素数组HashTable 结构内?
  • 为什么发生了什么?您实际上并没有告诉我们您观察到的不良行为。您一定已经观察到导致您出现问题的某些事情。那是什么东西
  • 我尝试在 HashTable @user3386109 中创建一个元素数组

标签: c dynamic hashtable dynamic-allocation


【解决方案1】:

您所做的是一个指向元素的指针数组。然而,init_hash 函数似乎需要一个元素数组。要创建元素数组,代码应如下所示。我添加了一些 cmets 以突出显示一些更改。

typedef struct element{
    char *key;
    char *value;
}element;

typedef struct HashTable{
    int size;
    element *arr_table;     // <-- only one '*', not two, to declare a pointer to an array of elements
}HashTable;

void init_hash(int size, HashTable *t)
{
    if (size < 1)
        return;
    t->size = size;
    t->arr_table = malloc(sizeof(element) * size);  // <-- allocate memory for the elements, note 'sizeof(element)' not 'sizeof(element *)'
    if (t->arr_table == NULL)
        return;
    int i;
    for (i = 0; i < size; i++)
    {
        t->arr_table[i].key = NULL;         // <-- table[i] is a structure, use dot notation
        t->arr_table[i].value = NULL;
    }
}

int main( void )    // <-- declare main with the correct signature
{
    HashTable *ht = malloc(sizeof(HashTable));  // <-- don't cast the return value from malloc
    int size_ht = 9;
    init_hash(size_ht, ht);
    printf("...\n");
}

【讨论】:

    猜你喜欢
    • 2023-03-04
    • 2013-08-20
    • 2012-10-03
    • 2019-03-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-07
    相关资源
    最近更新 更多