为什么我们在C中为链表定义Structure时不会出错

Dee*_*pak 4 c structure

以链接列表定义的结构为例...

struct test_struct                                         line 1    
{                                                          line 2    
    int val;                                               line 3
    struct test_struct *next;                              line 4
};                                                         line 5
Run Code Online (Sandbox Code Playgroud)

在第4行,由于test_struct甚至没有完全定义(我假设结构在第5行完全定义,因为';',之前我们不能说结构是定义的)那么为什么我们不会在第4行得到错误test_struct没有定义......?

P.P*_*.P. 5

确实,在struct test_struct结束之前没有完全定义,在第4行;,你只是定义了一个指向不完整类型指针,这很好.

要定义完整的类型对象struct test_struct,编译器需要知道有关该对象的完整信息.但是要定义指向某种类型的指针,则不需要它.

例如,你做不到:

struct test_struct                                         
{                                                          
    int val;                                               
    struct test_struct value;                              
};
Run Code Online (Sandbox Code Playgroud)

因为要定义value,需要有关对象类型的完整信息.但要定义struct test_struct*,它不是必需的.