62

Do standard C library implementations, especially glibc (the GNU C Library) provide linked lists, stack et al. data structures, or do we have to roll our own?

Thanks.

James Ko
  • 32,215
  • 30
  • 128
  • 239
rsjethani
  • 2,179
  • 6
  • 24
  • 30

6 Answers6

29

The C Standard does not provide data structures like linked list and stack.Some compiler implementations might provide their own versions but their usage will be non portable across different compilers.

So Yes, You have to write your own.

Alok Save
  • 202,538
  • 53
  • 430
  • 533
  • 2
    Ofcourse, If you are not bothered of portability just refer the target compiler documentation, find the suitable data structures it provides and use them. – Alok Save Dec 22 '12 at 09:52
28

The C standard doesn't, glibc however provides lists, tail queues, and circular queues in <sys/queue.h> according to the queue man page those come from BSD and not POSIX.

iabdalkader
  • 17,009
  • 4
  • 47
  • 74
22

There are hash tables, binary trees and binary search stuff in glibc. Those are part of C89, C99 and/or POSIX.1 standards. Some reason linked list is not there.

More info from man pages: hsearch, tsearch and bsearch

Note: Some of those have bad design. For example: hsearch allows only one hash table per process. The GNU compiler, gcc/glibc, provides reentrant versions hcreate_r, hsearch_r, and hdestroy_r that allow multiple hash tables. See also Stack Overflow's How to use hcreate_r.

Community
  • 1
  • 1
SKi
  • 8,007
  • 2
  • 26
  • 57
5

As such C does not provide data structures but you can use the glib provided by Gnome

Queue.h ad Tree.h also provides you some Data structures

Rahul Tripathi
  • 168,305
  • 31
  • 280
  • 331
2

There's a hash table implementation in POSIX (and GLibc); see the manpages for hcreate/hdestroy/hsearch.

But, as mentioned, using glib is probably the easiest way to save yourself from reimplementing the basic data structure.

djcb
  • 389
  • 1
  • 4
2

As other answers already stated, there isn't a linked list library in the standard library.

I've written one for my own use a while ago. You can freely use it or use the code as reference.

You can find it here: libllist

stdcall
  • 27,613
  • 18
  • 81
  • 125
  • And why should I trust you? Snark aside, I went looking for this question (and assume it was asked) b/c using a standard library feels safer than undertaking a custom implementation -- whether that implementation is mine or someone else's. – Alex Leibowitz Aug 27 '22 at 16:39
  • @AlexLeibowitz Don't trust me. it's open source. feel free to look at the code. – stdcall Aug 27 '22 at 19:16