简体   繁体   中英

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...?

It's true that the struct test_struct is not fully defined before the closing ; , at line4 you are only defining a pointer to an incomplete type , which is fine.

To define a complete object of type struct test_struct , compiler needs to know the complete information about that object. 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. But to define struct test_struct* , it's not required.

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)! Self referenced structures usually need to be handled using dynamic memory handle subroutines like free and 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM