简体   繁体   中英

why are the structs in c++ used as a pointer?

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

we use this struct as Node* node and not Node node.why? any link to a reference would also be appreciated

I don't think so. This is sample for make a link list struct. When you want to make a list with count of list is not defined. you can using struct: Node *next pointer. this pointer will be save address of next element of list. So that, you can access next element from head element. if you use Node next; next is only a variable.

The other comments already pointed this out, somewhat. When you define a struct, the compiler needs to know how much memory is needed to store an object of this new struct type.

However, if your struct contains another struct of the same type (direct or indirect) the compiler is unable to calculate the size needed for instantiating an object (understandably, since its size would vary depending on how many times this is chained).

So in order to be able to allocate enough memory for an object, you need to use a pointer. The size of this pointer in memory is known at compile time (no matter where it points at, even if it is Null), so the compiler knows how much memory to allocate for each Node object you create.

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