0

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

这是我应该做的:

/**
 * 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;
}

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

4

1 回答 1

0

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

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

这是我编写此代码的方式:

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;
}
于 2015-09-01T13:14:14.557 回答