Generic list manipulation function in C?

后端 未结 7 783
独厮守ぢ
独厮守ぢ 2020-12-16 05:53

What is a generic list manipulation function in C? (I saw this when I was going through some materials.)

What is the difference between this function and a function

7条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-16 06:45

    C has no concept of "generic" pointers or objects - the closest you can get is using a void* pointer. If you want one piece of code to be able to handle any data type, you pretty much have to use void* pointers. For data types with sizes no larger than a pointer, you can cast between the type and void*; for larger data types, you'll have to use dynamic memory and have the void* member point to the dynamic memory. Just watch out for memory leaks!

    typedef struct list_node {
      struct list_node *next;
      void *data;
    } list_node;
    
    void list_insert(list_node *node, void *data) {
      // ...
    }
    

    On the other hand, if you want to generate code for each possible data type, you'll have to do it with macros, and then instantiate the macros for each data type you might use. For example:

    #define DEFINE_LIST(type) \
      typedef struct list_node_##type { \
        struct list_node_##type *next; \
        type data; \
      }
    
    #define IMPLEMENT_LIST_INSERT(type) \
      void list_##type##_insert(list_node_##type *node, type data) { \
        ... \
      }
    
    DEFINE_LIST(int);     // defines struct list_node_int
    DEFINE_LIST(double);  // defines struct list_node_double
    IMPLEMENT_LIST_INSERT(int);    // defines list_int_insert
    IMPLEMENT_LIST_INSERT(double); // defines list_double_insert
    

提交回复
热议问题