Self referring structure declaration

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

    node in struct node is a "struct tag", which at the point you write it creates an "incomplete type": a struct variable which is not at this point declared, but not defined. The type is not complete before the final }; of your struct.

    In C, an incomplete type can be referenced even before it is fully defined, by using a pointer to that type. You can however not allocate a variable (instance) of that type, because the actual struct definition is yet to be defined. (It works exactly like abstract base classes in C++, if you are familiar with those.)

    So when you write

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

    the row struct node *next means "here is a pointer to a struct node, even though I have no idea how that type is defined yet". But you cannot declare a variable of type struct node inside the struct definition of that very same type, simply because you cannot use something before you have created it.

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