Self referring structure declaration

前端 未结 7 877
没有蜡笔的小新
没有蜡笔的小新 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: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 */
    

提交回复
热议问题