362 views

2 Answers

Best answer
2 votes
2 votes
When we use Structure and pointer to implement linked list we use malloc

We are implementing Linked list using pointer, simply creating an pointer does not give it any memory

We want Memory to store some meaningful data in that pointer as well as information regarding pointers next to it

Eg:

struct node{

int data;

struct node *next;

}

Above code defines a node, i.e node will contain two parameters 1) data and 2) pointer to next node.

But while implementing it we must have some memory reserved for node: assuming int takes 2 byte and pointer to next node takes 2 byte

head=(struct node*)malloc(sizeof(struct node));

above line gives head 4 byte of space in Memory; now we can store a integer and pointer to next element of list in head node
selected by
1 votes
1 votes
The real purpose of used linked list is have to dynamic memory allocation . So to  use node to allocate dynamic memory in  a linked list we use malloc (). When you use malloc()  it allocates extra memory space than you asked for.

Related questions

0 votes
0 votes
0 answers
4
teja1521 asked Feb 17, 2019
1,736 views