self referential struct definition?

后端 未结 9 1742
死守一世寂寞
死守一世寂寞 2020-11-22 11:09

I haven\'t been writing C for very long, and so I\'m not sure about how I should go about doing these sorts of recursive things... I would like each cell to contain another

9条回答
  •  星月不相逢
    2020-11-22 11:54

    All previous answers are great , i just thought to give an insight on why a structure can't contain an instance of its own type (not a reference).

    its very important to note that structures are 'value' types i.e they contain the actual value, so when you declare a structure the compiler has to decide how much memory to allocate to an instance of it, so it goes through all its members and adds up their memory to figure out the over all memory of the struct, but if the compiler found an instance of the same struct inside then this is a paradox (i.e in order to know how much memory struct A takes you have to decide how much memory struct A takes !).

    But reference types are different, if a struct 'A' contains a 'reference' to an instance of its own type, although we don't know yet how much memory is allocated to it, we know how much memory is allocated to a memory address (i.e the reference).

    HTH

提交回复
热议问题