[英]how come we don't get error when we define Structure in C for linked list
Take the example of structure defined for a linked list... 以链接列表定义的结构为例...
struct test_struct line 1
{ line 2
int val; line 3
struct test_struct *next; line 4
}; line 5
At line 4, since test_struct is not even fully defined (I am assuming structure is fully defined at line 5 because of ';', before that we cannot say structure is defined) then how come we don't get error at line 4 that test_struct is not defined...? 在第4行,由于test_struct甚至没有完全定义(我假设结构在第5行完全定义,因为';',之前我们不能说结构是定义的)那么为什么我们不会在第4行得到错误test_struct没有定义......?
It's true that the struct test_struct
is not fully defined before the closing ;
确实
struct test_struct
在结束之前没有完全定义;
, at line4 you are only defining a pointer to an incomplete type , which is fine. 在第4行,你只是定义了一个指向不完整类型的指针 ,这很好。
To define a complete object of type struct test_struct
, compiler needs to know the complete information about that object. 要定义
struct test_struct
类型的完整对象,编译器需要知道有关该对象的完整信息。 But to define a pointer to some type, it's not needed. 但是要定义指向某种类型的指针,则不需要它。
For example, you can't do: 例如,你做不到:
struct test_struct
{
int val;
struct test_struct value;
};
because to define value
, the complete information about the object's type is needed. 因为要定义
value
,需要有关对象类型的完整信息。 But to define struct test_struct*
, it's not required. 但是要定义
struct test_struct*
,它不是必需的。
In your example you define a self reference structure. 在您的示例中,您定义了一个自引用结构。 A self reference structure contains one or more pointer(s) to itself (as you define in line 4)!
自引用结构包含一个或多个指针(如第4行所定义)! Self referenced structures usually need to be handled using dynamic memory handle subroutines like free and malloc.
自引用结构通常需要使用动态内存句柄子例程(如free和malloc)来处理。 In your case you just define a pointer to a type which handled in time when your file has been complete.
在您的情况下,您只需定义一个指向类型的指针,该类型在文件完成时及时处理。 At compile time, C compiler calculates memory bytes which your pointers need to point that and at that time your structure has been defined exactly.
在编译时,C编译器计算指针需要指向的内存字节,并且在那时您的结构已经完全定义。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.