Self referring structure declaration

前端 未结 7 736
没有蜡笔的小新
没有蜡笔的小新 2021-01-21 04:00

The follwing declaration is valid.

struct node
{
    int a;
    struct node *next;
};

However, when we define the following, it gives error.

相关标签:
7条回答
  • 2021-01-21 04:11

    Your second declaration would define a struct which is infinitely deeply nested, which is impossible.

    0 讨论(0)
  • 2021-01-21 04:12

    Infinite nodes inside a node? Does that make sense? What will be the size of "struct node"?

    0 讨论(0)
  • 2021-01-21 04:15

    This is the same case as with forward declaration of class/struct type:

    struct node;
    
    struct node* node_ptr; /* is valid */
    struct node node_instance; /* is invalid */
    

    So struct node; basically says: hey there is a structure defined somewhere outside this file. The type is valid, pointers may be used, but you cannot instantiate the object.

    This is because the size of the pointer is known and is specific to the target architecture (e.g. 32 or 64-bit). The size of the structure is unknown until declared.

    When you declare the type completey, then you will be allowed to declare the object of that type:

    struct node {
      int a;
      struct node* b; /* this will work, but the size of struct is unknown yet */
    }
    
    struct node* node_ptr; /* this works always with full and forward declarations */
    struct node node_object; /* now, the size of struct is known, so the instance may be created */
    
    0 讨论(0)
  • 2021-01-21 04:20

    Pointer store address, struct has structure. If declared like struct it would be recursive and infinite. If declared like pointer it refers to other structure somewhere else.

    0 讨论(0)
  • 2021-01-21 04:32

    You can't have structure that contains itself as a member:

    struct node
    {
        int a;
        struct node next;
    };
    

    Think about this question: if it is possible, what is the size of such structure? struct node contains struct node next as a member, then the member next would contain a member of type struct node as well, and so on and on and on... The size would be infinite.

    0 讨论(0)
  • 2021-01-21 04:32

    it should be like this:

    struct node {
      int a;
      struct node *next;
    };
    

    this works,

    but

    struct node {
      int a;
      struct node next;
    };
    

    cannot be understood by the compiler as node becomes recursive structure, and the compiler does not know how much memory to allocate for node.

    However, if you use a pointer, it understands that the size of a pointer is equal to size of the memory to be addressed, and hence reserves that space, regardless of if node is a complete struct.

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