Does C have hash/dictionary data structure?

13,156

Solution 1

Basically, the only data structure that C has are arrays, structs (which is kind of like a map, but the keys must be known at compile time) and unions. Everything else must be coded manually or provided by a library.

Solution 2

It's not part of standard C libraries. Use a library such as Glib.

Solution 3

Ignore all the above misleading answers, C does have a standard library for this, long before all those fancy languages existed. The basic version only does one table, the GNU version as many as you want.

#include <search.h>

int hcreate(size_t nel);

ENTRY *hsearch(ENTRY item, ACTION action);

void hdestroy(void);

#define _GNU_SOURCE         /* See feature_test_macros(7) */
#include <search.h>

int hcreate_r(size_t nel, struct hsearch_data *htab);

int hsearch_r(ENTRY item, ACTION action, ENTRY **retval, struct hsearch_data *htab);

void hdestroy_r(struct hsearch_data *htab);

checkout the:

https://pubs.opengroup.org/onlinepubs/9699919799/functions/hcreate.html

Share:
13,156
olala
Author by

olala

Learning programming, computation, data analysis, so much to learn but I'm enjoying it!

Updated on June 28, 2022

Comments

  • olala
    olala almost 2 years

    I'm learning C now coming from knowing perl and a bit python. I did a quick search and found there is no explicit hash/dictionary as in perl/python and I saw people were saying you need a function to look up a hash table. So the fact is C doesn't provide an inherent hash structure and you have to write some function to be able to use hash in C?

  • gnash117
    gnash117 about 11 years
    I think Oswald gave a better answer but you gave the OP a solution if they want that type of functionality stackoverflow.com/questions/2540/good-stl-like-library-for-c