6

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?

Gaurang Tandon
  • 6,504
  • 11
  • 47
  • 84
olala
  • 4,146
  • 9
  • 34
  • 44
  • 3
    Yes, C standard library does not provide any such data structure but You might use some non standard library which provides the functionality. – Alok Save Apr 22 '13 at 15:29
  • 1
    possible duplicate of [Hashtable as part of Standard C Library?](http://stackoverflow.com/questions/6118539/hashtable-as-part-of-standard-c-library) – djechlin Apr 22 '13 at 16:52

4 Answers4

8

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.

Oswald
  • 31,254
  • 3
  • 43
  • 68
5

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

Zombo
  • 1
  • 62
  • 391
  • 407
4

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

djechlin
  • 59,258
  • 35
  • 162
  • 290
  • I think Oswald gave a better answer but you gave the OP a solution if they want that type of functionality http://stackoverflow.com/questions/2540/good-stl-like-library-for-c – gnash117 Apr 22 '13 at 16:05
0

I would recommend you to take a look at a very nice library GLib:

GLib is a general-purpose utility library, which provides many useful data types, macros, type conversions, string utilities, file utilities, a mainloop abstraction, and so on. It works on many UNIX-like platforms, as well as Windows and OS X. GLib is released under the GNU Library General Public License (GNU LGPL).

There are many OpenSource projects that use this library: GNOME, Wireshark and many more. Glib includes implementations of a number of useful data structures, such as:

  • Hash table (GHashTable)
  • Doubly-Linked List (GList)
  • Queue (QQueue)
  • Dataset
  • etc
Paul
  • 1,262
  • 8
  • 16