Why would I use malloc when same job can be done by without malloc as below..
#include
#include
struct node {
int data;
Your data type looks like a node in a tree. Two primary reasons to use malloc
for tree node allocations would be
To allocate the arbitrary number of nodes. The number of tree nodes will in general case be a run-time value. For this reason, it is impossible to declare the proper number of local variables for such nodes since all local variables have to be declared at compile time. Meanwhile, malloc
can be called in run-time as many times as you want, allocating as many node object as you need.
To make sure that the node does not be destroyed automatically when the lifetime of the local object ends (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 object will transcend the block boundaries and function boundaries. Nothing like that is possible with local objects, since local objects are automatically destroyed at the end of their block.
Your code sample does not depend on any of the benefits of dynamic allocation, since it doe snot really create a real tree. It just declared as single node. But if you attempt to build a full tree with run-time number of nodes, yo will immediately realize that it is impossible to do by declaring nodes as local objects. You will unavoidably have to allocate your nodes using malloc
.
Your "how n1 which is not initialized to memory location is able to store data" question must be caused by some confusion. struct node n1;
is an object definition, which means that it assigns a memory location for n1
. That's exactly the purpose of object definition.