how to use the GNU hcreate_r

拟墨画扇 提交于 2019-12-05 10:45:39

First off, you will need to add the #define _GNU_SOURCE macro in order to access the GNU extensions properly. ie:

#define _GNU_SOURCE
#include <search.h>

Then you need to understand the documentation:

Function: int hcreate_r (size_t nel, struct hsearch_data *htab)

The hcreate_r function initializes the object pointed to by htab to contain a 
hashing table with at least nel elements. So this
function is equivalent to the hcreate function except that the
initialized data structure is controlled by the user.

This allows having more than one hashing table at one time. 
The memory necessary for the struct hsearch_data object can be allocated
dynamically. It must be initialized with zero before calling this
function.

The return value is non-zero if the operation was successful. 
If the return value is zero, something went wrong, which probably means
the programs ran out of memory.


So unlike hcreate, you are providing the hashing table data structures. Further, those structures should be initialised to zero. So then you probably want to do something like this:

//dynamically create a single table of 30 elements 
htab=calloc(1,sizeof(struct hsearch_data));
resultOfHcreate_r=hcreate_r(30,htab);

//do some stuff

//dispose of the hash table and free heap memory
hdestroy_r(htab);
free(htab)
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!