Memory allocation problem in HashTable

后端 未结 4 439
清歌不尽
清歌不尽 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:34

    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.

    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.

提交回复
热议问题