HashTable中的内存分配问题 [英] Memory allocation problem in HashTable

查看:121
本文介绍了HashTable中的内存分配问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请不要关闭这句话,

Please don't close this saying a duplicate question. I made an important change so not to confuse people, I resubmitted this much clearer codes.

请帮助我解决此内存分配问题.我正在处理HashTable,这就是我的工作(仅限部分代码)

Please help me to solve this memory allocation problem. I'm working on a HashTable and this is what I've (partial codes only)

main.c

HashTablePtr hash;
hash = createHashTable(10);
insert(hash, "hello");
insert(hash, "world");

HashTable.c

    HashTablePtr createHashTable(unsigned int capacity){
    HashTablePtr hash;
    hash = (HashTablePtr) malloc(sizeof(HashTablePtr));
    hash->size = 0;
    hash->capacity = capacity;          
    hash->list = (ListPtr *)calloc(capacity, sizeof(List)); /*NO MEMORY ALLOCATION HERE*/
    return hash;

List.h

typedef struct list List;
typedef struct list * ListPtr;

struct list {
    int size;
    NodePtr head;
    NodePtr tail;
};
...
...

HashTable.h

    typedef struct hashtable * HashTablePtr;
    typedef struct hashtable HashTable;
    struct hashtable {
        unsigned int capacity;
        unsigned int size;
        ListPtr *list;
        unsigned int (*makeHash)(unsigned int, void *);
    };
...
...

当我运行调试器(Netbeans C/C ++调试器)时,没有看到任何内存分配给hash-> list.在上面的示例中,我试图将其设置为10个列表的数组.

When I run my debugger (Netbeans C/C++ debugger, I see no memory being allocated to hash->list. In above example, my attempt is to make it an array of 10 lists.

请帮助我解决这个问题.

Please help me to solve this.

如果有帮助,我不是C方面的专家.

I'm not that expert in C, if that helps.

推荐答案

您也可以使用的一个不错的习惯用法例如:

One nice idiom that you can use as well is eg:

hash = (HashTablePtr) malloc(sizeof(*hash));

通过不对分配中的任何类型进行硬编码,可以大大减少混淆的可能性.

By not hard-coding any types in the allocation, the possibility of mixing things up is greatly reduced.

请注意,这里实际上并未取消引用'hash'-sizeof()始终在编译时求值,因此编译器只需弄清楚* hash/would/具有的类型,并获取其大小即可.

Note that 'hash' is not actually dereferenced here - sizeof() is always evaluated at compile time, so the compiler just figures out what type *hash /would/ have, and gets the size of that.

这篇关于HashTable中的内存分配问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆