What is self-referencing structure in C?

前端 未结 3 554
甜味超标
甜味超标 2020-12-11 14:24
struct LinkedList  
{  
    int data;
    struct LinkedList *next;
};

In the code, within the definition of struct LinkedList there is

3条回答
  •  生来不讨喜
    2020-12-11 14:42

    So, the code

    struct LinkedList  
    {  
        int data;
        struct LinkedList *next;
    };
    

    defines a struct type containing two members named data and next, with the next member storing the address of a different object of the same type. Given the code:

    struct LinkedList Node1 = { .data = 1, .next = NULL };
    struct LinkedList Node0 = { .data = 0, .next = &Node1 };
    

    you get something that sort of looks like this:

    Node0              Node1
    +---+--------+    +---+------+
    | 0 | &Node1 |--->| 1 | NULL |
    +---+--------+    +---+------+
    

    (Note that you would never create a linked list this way, this is just for illustration).

    This is possible for two reasons:

    1. C allows you to declare pointers to incomplete types;
    2. Pointers to struct types all have the same size and representation.

    This is an example of a self-referential data type, which simply means that the type stores a reference (pointer) to a different object of the same type.

提交回复
热议问题