Why do we need self-referential structure?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • sathishc58
    New Member
    • Sep 2007
    • 34

    Why do we need self-referential structure?

    Hi All,

    We know what is self-referential structure and it is widely used in creating data structure (for ex: linked-list)

    struct xxx
    {
    int a;
    struct xxx *ptr;
    }

    Why should I declare "ptr" to be of the same type. Cannot I declare "ptr" as "int" or "void" as it is going to store only the address.

    I searched net, but most of the pages explain self-referential structure but I could not find the reason.

    Thanks & Regards
    Sathish Kumar
  • Banfa
    Recognized Expert Expert
    • Feb 2006
    • 9067

    #2
    You declare pointer as the type it will be pointing to, that is struct xxx. Since the C (and C++) standard does not guarantee that you can safely cast a pointer to a type to anything other than void and that you can only safely cast a void pointer back to a pointer to the type it originally pointed to your only safe options when creating a linked list would be struct xxx* and void*.

    If you used void* you would have to put a cast into the code everywhere you used it which would make the code extremely messy and unmaintainable. So of the 2 safe options it makes sense to struct xxx* in order to keep the code clean.

    Comment

    • donbock
      Recognized Expert Top Contributor
      • Mar 2008
      • 2427

      #3
      "Why should I declare "ptr" to be of the same type. Cannot I declare "ptr" as "int" or "void" as it is going to store only the address."

      The ptr field is a pointer to another instance of the structure. With enough engenuity you could manage to coerce a different data type to act like a pointer-to-structure, but why go through the effort (and risk)?

      Comment

      Working...