Search code examples
c++pointersstructureself-reference

How does memory work in declaration of structure which uses self-referential structure pointer in C/C++?


In declaration of structure in C/C++, we have to use a self-referential structure pointer instead of a structure itself.

// compile error

struct stack {
    int overflow;
    stack p;
}

struct stack {
    int overflow;
    stack* p;
}

One brings about the error but the other doesn't under the same condition(declaration) I'm curious about the operation of memory areas when use stack* p; during the declaration and how to make it possible.


Solution

  • This

    struct stack {
        int overflow;
        stack p;
    }
    

    Tries to contains itself , so how big should it be? With one copy of itself it would look line this

     int ov;
     {
         int ov;
         stack p;
     }
    

    but that stack p needs to be expanded - so we get

     int ov;
     {
         int ov;
        {
             int ov;
             stack p;
        }
     }
    

    but that stack p needs to be expanded - so we get

     int ov;
     {
         int ov;
        {
             int ov;
             {
                 int ov;
                 stack p;
              }
        }
     }
    

    but that stack p needs to be expanded - so we get ...... forever.

    Look at another way, how many int overflows should the struct contain?

    The pointer one works like this

      int overflow;
      stack *p;
    

    The end. The struct is of a well defined size an integer and a pointer