Home > Blockchain >  why are the structs in c used as a pointer?
why are the structs in c used as a pointer?

Time:06-06

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

CodePudding user response:

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.

CodePudding user response:

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.

  • Related