'Multipurpose' linked list implementation in pure C

前端 未结 9 1802
一生所求
一生所求 2020-12-12 16:33

This is not exactly a technical question, since I know C kind of enough to do the things I need to (I mean, in terms of not \'letting the language get in your way\'), so thi

相关标签:
9条回答
  • 2020-12-12 17:24

    I haven't coded C in years but GLib claims to provide "a large set of utility functions for strings and common data structures", among which are linked lists.

    0 讨论(0)
  • 2020-12-12 17:25

    My $.002:

    • Making a list of void pointers (kinda diselegant; harder to debug)

    This isn't such a bad choice, IMHO, if you must write in C. You might add API methods to allow the application to supply a print() method for ease of debugging. Similar methods could be invoked when (e.g.) items get added to or removed from the list. (For linked lists, this is usually not necessary, but for more complex data structures -- hash tables, for example) -- it can sometimes be a lifesaver.)

    • Making only one list, but having a union as 'element type', containing all element types I will use in the program (easier to debug; wastes space if elements are not all the same size)

    I would avoid this like the plague. (Well, you did ask.) Having a manually-configured, compile-time dependency from the data structure to its contained types is the worst of all worlds. Again, IMHO.

    • Using a preprocessor macro to regenerate the code for every type, in the style of SGLIB (sglib.sourceforge.net), 'imitating' C++'s STL (creative solution; doesn't waste space; elements have the explicit type they actually are when they are returned; any change in list code can be really dramatic)

    Intriguing idea, but since I don't know SGLIB, I can't say much more than that.

    • Your idea/solution

    I'd go with the first choice.

    0 讨论(0)
  • 2020-12-12 17:27

    This is a good problem. There are two solutions I like:

    • Dave Hanson's C Interfaces and Implementations uses a list of void * pointers, which is good enough for me.

    • For my students, I wrote an awk script to generate type-specific list functions. Compared to preprocessor macros, it requires an extra build step, but the operation of the system is much more transparent to programmers without a lot of experience. And it really helps make the case for parametric polymorphism, which they see later in their curriculum.

      Here's what one set of functions looks like:

      int      lengthEL (Explist *l);
      Exp*     nthEL    (Explist *l, unsigned n);
      Explist *mkEL     (Exp *hd, Explist *tl);
      

      The awk script is a 150-line horror; it searches C code for typedefs and generates a set of list functions for each one. It's very old; I could probably do better now :-)

    I wouldn't give a list of unions the time of day (or space on my hard drive). It's not safe, and it's not extensible, so you may as well just use void * and be done with it.

    0 讨论(0)
提交回复
热议问题