Memory allocation problem in HashTable

后端 未结 4 393
清歌不尽
清歌不尽 2021-01-24 17:18

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.

4条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-24 17:40

    In this line:

    hash->list = (ListPtr *)calloc(capacity, sizeof(List));
    

    The calloc function will allocate some memory for List, then return a pointer to the allocated memory, which would be List* (or, equivalent to ListPtr due to the typedef.)

    In the code, the pointer is then casted to (ListPtr*), which would actually be List** which is not the type List* which is expected. Therefore, change the ListPtr* to ListPtr and see if that would fix that line.

    Edit

    As pointed out by leiz and Klathzazt in the comments, the Hashtable.list type is ListPtr* or List**:

    struct hashtable {
        ...
        ListPtr *list;
    

    This would be the reason why trying to assign a ListPtr type returned and casted from calloc would cause a compiler error. Rather than storing a pointer to a pointer of a List in the Hashtable, it should just hold a pointer to the list:

    struct hashtable {
        ...
        ListPtr list;
    

    This should eliminate the compiler error, as the type of Hashtable.list and typecast both will be ListPtr.

提交回复
热议问题