c - 为什么这段代码不在 C 中分配内存?

标签 c memory hashtable allocation

更新的问题在这里

Memory allocation problem in HashTable

我正致力于用 C 语言制作哈希表。这就是我所做的。我认为我正走在正确的道路上,但是当我尝试这样做时

ma​​in.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;
    ListPtr mylist = (ListPtr)calloc(capacity, sizeof(ListPtr)); /* WHY IT DOESN'T ALLOCATE MEMORY FOR mylist HERE?? */
    mylist->head = NULL;
    mylist->size = 0;
    mylist->tail = NULL;    
    hash->list = mylist;  
    return hash;

ListPtr 是一个链表指针

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 *);
    };
...
...

当我运行调试器时,我发现没有内存分配给 myList。在上面的例子中,我的尝试是让它成为一个包含 10 个列表的数组。

请帮我解决这个问题。

如果有帮助的话,我不是 C 专家。

最佳答案

calloc(capacity, sizeof(ListPtr)

应该是

calloc(capacity, sizeof(List)

关于c - 为什么这段代码不在 C 中分配内存?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/827986/

相关文章:

c - 哈希表还是 BST?

c - 使用libvirt API在C程序中获取KVM虚拟机域名

c - 如何确保两种类型具有相同的大小?

c - char *derp[20] 是什么意思?

C - 初始化哈希表

performance - 为超大数据选择数据结构

c - 使用函数修改结构体中字符串的内容

java - java中可以有多个堆吗?

c - malloc 对象上的 Free throws 错误

c - 强制 free() 将 malloc 内存返回给操作系统