C double linked list with abstract data type

后端 未结 5 622
暖寄归人
暖寄归人 2020-12-14 05:08

i need in double linked list in C, but it must be for different types. In C++ we use templates for it. Where can i find example in C for double linked list with abstract typ

5条回答
  •  囚心锁ツ
    2020-12-14 05:20

    The closest think in C to an "object" base class or templated types is a void pointer. A void * represents a pointer to something, but it does not specify what type of data is being pointed to. If you want to access the data, you need to use a cast.

    A doubly linked list node could look like this:

    struct DoubleLinkedListNode {
        struct DoubleLinkedListNode *previous, *next;
        void *data;
    };
    

    To assign a node a string, for example, you could do:

    char myString[80] = "hello, world";
    struct DoubleLinkedListNode myNode;
    myNode.data = myString;
    

    To get the string back from a node, you use a cast:

    char *string = (char *)myNode.data;
    puts(string);
    

    To store a non-pointer, you need to make a pointer from the data. For structures, you may be able to simply dereference the instance if its lifetime is long enough (similar to the above example). If not, or if you're dealing with a primitive type (e.g. an int or float), you need to malloc some space. Just be sure to free the memory when you're done.

提交回复
热议问题