In the following program :
// illustration of linked list
#include <iostream>
using namespace std;
struct node {
int data;
struct node* next;
};
struct node* buildList();
int main() {
struct node* head = buildList();
cout << head->data;
}
struct node* buildList() {
struct node* head = NULL;
struct node* second = NULL;
struct node* third = NULL;
head = new node; // builds up a pointer structure on heap
second = new node;
third = new node;
head->data = 1;
head->next = second;
head->data = 2;
second->next = third;
head->data = 3;
third->next = NULL;
return head;
}
i am unaware of the new operator’s work here. What task they perform ? (I read that it allocates space on heap.But i don’t know what does it mean) If i remove these statements there is no output and the program crashes. Why is that ?
The head, second, and third variables are pointers to nodes in memory. But, before you can use them, they must be pointing at a valid node in memory. This is where the new operator comes in. The heap is just an area of memory that has been allocated to your program to dynamically create objects (as opposed to the stack. See here for the difference).