Why would I use malloc when same job can be done by without malloc as below..
#include
#include
struct node {
int data;
int main() {
struct node n1;
n1.data = 99
This reserves space on the stack (in main
's frame) equivalent to the size of a struct node
. This is known as a local, and it only exists within the context of main
.
struct node *n2 = (struct node *) malloc (sizeof(struct node));
This is an allocation on the heap. This memory exists no matter what function context you are in. This is typically called "dynamic allocation".
These node
structures are the basis for a linked list, which can have nodes added, removed, re-ordered, etc. at will.
See also: