The data type looks like a node in a tree. The two main reasons for using malloc for a node tree would be
To select an arbitrary number of nodes. The number of tree nodes will generally be a run-time value. For this reason, it is not possible to declare the correct number of local variables for such nodes, since all local variables must be declared at compile time. Meanwhile, malloc can be called at run time as many times as you want, allocating as many node objects as you need.
To make sure that the node will not be automatically destroyed when the local object expires (i.e. at the end of the block). Objects allocated by malloc live forever, i.e. Until you destroy them explicitly by calling free . Such an object will exceed the boundaries of blocks and the boundaries of functions. Something similar is possible with local objects, since local objects are automatically destroyed at the end of their block.
Your sample code does not depend on any of the benefits of dynamic allocation, since it really creates a real tree. It is simply declared as a single node. But if you try to build a complete tree with the number of nodes at runtime, yo will immediately realize that it is impossible to do this by declaring the nodes as local objects. You will inevitably have to allocate your nodes using malloc .
Your "like n1, which is not initialized in a memory location capable of storing data", should be caused by some confusion. struct node n1; is the definition of an object, which means that it assigns a memory location for n1 . It is the purpose of determining the object.
source share