【问题标题】:how can i create a dynamic array of a hash table in c如何在c中创建哈希表的动态数组
【发布时间】:2012-02-09 12:52:06
【问题描述】:

我设置了以下存储桶条目结构和哈希表

typedef struct Hash_Entry
{
    struct Hash_Entry *next;    
    void        *key_Data;  
    unsigned    key_hash;   
    char        key[5]; 
} Hash_Entry;

typedef struct Hash_Table 
{
    struct Hash_Entry **bucketPtr;  /* Buckets in the table */
    int         size;       /* Actual size of array. */
    int         numEntries; /* Number of entries in the table. */
    int         mask;       /* Used to select bits for hashing. */
} Hash_Table;

我想为这个 Hash_Table 创建一个数组(或动态数组),这样当我觉得表已满时,我可以创建另一个表而不是调整它的大小

【问题讨论】:

    标签: c arrays hashtable dynamic-arrays


    【解决方案1】:

    您可以使用 stdlib 中的 malloc 创建一个数组

    Hash_Table* array = (Hash_Table*)malloc(sizeof(Hash_Table) * 100);
    

    当数组已满时,您可以执行重新分配。

    你可以看看:

    Create dynamic sized array of user defined structure

    【讨论】:

    • 他说他不想调整那个大小。
    【解决方案2】:

    类似:

    void hash_table_init(Hash_Table *table, size_t entries)
    {
      size_t i;
    
      table->size = 0;
      table->numEntries = entries;
      table->bucketPtr = malloc(table->numEntries * sizeof *table->bucketPtr);
      for(i = 0; i < table->numEntries; i++)
        table->bucketPtr[i] = NULL;
      table->mask = 0; /* Not sure how to initialize this. */
    }
    

    我不太明白将初始存储桶作为指针保留的意义,我可能会这样做

    typedef struct {
      ...
      Hash_Entry *buckets;
      ...
    } Hash_Table;
    

    假设实际上会使用大多数存储桶,那么为什么不拥有它们。 :)

    【讨论】:

      猜你喜欢
      • 2014-04-13
      • 2012-05-20
      • 2012-06-29
      • 2018-01-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-04-20
      • 2021-02-15
      相关资源
      最近更新 更多