Search code examples
cpointersstructdeclarationincomplete-type

What is the meaning of pointer to non-existing struct as a member-variable in another struct?


I have seen blocks of code in C like this:

struct Struct1
{
    struct Struct2* var;
}

and I wonder what exactly is the meaning of Struct2 in this example.In this code that is the first time when the name Struct2 is used.


Solution

  • The type struct Struct2 is an incomplete type (provided that there is no definition of the structure before the declaration of the structure Struct1). It can be defined somewhere else if the definition of the structure is required. But a pointer to this type like that

    struct Struct2 *var;
    

    is a complete type.

    For example you can declare a structure struct List the following way

    struct List
    {
        struct Node *head;
        struct Node *tail;
    };
    

    In this declaration there is not required the complete definition of the structure struct Node. The structure struct List contains two pointers to the first and the last nodes of a list.

    And then somewhere below or even in another header you can define the structure struct Node like for example

    struct Node
    {
        int data;
        struct Node *next;
    };