Type-safe generic data structures in plain-old C?

后端 未结 10 2165
庸人自扰
庸人自扰 2020-12-04 08:23

I have done far more C++ programming than \"plain old C\" programming. One thing I sorely miss when programming in plain C is type-safe generic data structures, which are p

10条回答
  •  日久生厌
    2020-12-04 09:00

    You could check out https://github.com/clehner/ll.c

    It's easy to use:

    #include 
    #include 
    #include "ll.h"
    
    int main()
    {
       int *numbers = NULL;
       *( numbers = ll_new(numbers) ) = 100;
       *( numbers = ll_new(numbers) ) = 200;
    
       printf("num is %d\n", *numbers);
       numbers = ll_next(numbers);
       printf("num is %d\n", *numbers);
    
       typedef struct _s {
          char *word;
       } s;
    
       s *string = NULL;
       *( string = ll_new(string) ) = (s) {"a string"};
       *( string = ll_new(string) ) = (s) {"another string"};
    
       printf("string is %s\n", string->word);
       string = ll_next( string );
       printf("string is %s\n", string->word);
    
       return 0;
    }
    

    Output:

    num is 200
    num is 100
    string is another string
    string is a string
    

提交回复
热议问题