使用struct的Hashtable

时间:2013-03-14 17:56:04

标签: c

我正在研究散列表,但没有走得太远。我的问题是如何将表格设置为大小。 (请阅读以下说明以获得澄清)。

这就是我应该做的:

/**
 * Create a new instance of struct hashStorage and return it. It sets the size of the
 * table to be of length "size" which will be the number of the entries in the hash. It takes also an
 * argument to specify the format of the order printed to an output stream. If myHash parameter
 * is NULL then this means that the hash should be a linked list. When myHash is NULL the size
 * parameter should be ignored.
 */

struct hashStorage {
    int    (*funcHash)  (int);
    void   (*printItem) (struct order *, FILE *);
    struct onode**      table;
    int    size;
};

struct hashStorage* createHash(int size, int (*myHash)(int),void(*printOrder)(struct order *, FILE *))
{
     struct hashStorage* hashList = (struct hashStorage*) malloc(sizeof(struct hashStorage));

     hashList->table;

    if(myHash == NULL)
    {

    }
    else
    {

    }
     return hashList;
}

如果有人可以解释我给予和示例将是一个很大的帮助。

1 个答案:

答案 0 :(得分:0)

您试图设置已分配对象的值。你面临的障碍是:

  1. 出于某种原因,您想要合并链表和哈希表数据结构?这是愚蠢的,但无论如何......
  2. malloc并不一定会返回指向对象的指针;它可能会返回NULL。你需要在继续之前检查一下。
  3. 您指定malloc的返回值的对象不是您要分配的对象,因此hashList = ...无法正常工作;您需要使用*hashlist = ...hashlist->member = ...
  4. 以下是我将如何编写此代码:

    typedef size_t hash_fn(int);
    typedef void print_fn(struct order *, FILE *);
    
    struct hash_table {
        size_t       size;
        hash_fn      *hash_function;
        print_fn     *print_function;
        struct onode *item[];
    };
    
    struct hash_table *create_hash_table(size_t size, hash_fn *hash_function, print_fn *print_function)
    {
        if (hash_function == NULL)
        {
            /* This should give you enough to implement your linked list;
             * use hash_table->item[0] as your item and hash_table->item[1]
             * as your link. */
            size = 2;
        }
    
        struct hash_table *hash_table = malloc(sizeof *hash_table
                                             + size * sizeof *hash_table->table);
        if (hash_table == NULL)
        {
            return NULL;
        }
    
        *hash_table = (struct hash_table) { .size = size
                                          , .hash_function = hash_function
                                          , .print_function = print_function };
    
        return hash_table;
    }