piyush172
piyush172

Reputation: 100

Difference between int* a and int* a =new int

I m studying Binary Search Tree just had little Doubt, here is struct to construct a node.

struct Node 

    { 
        int data; 
        Node* left, *right; 
    }; 

Now My doubt is when I m creating a new node why do I have to write

Node* node =new Node;

Why not

Node* node;

Upvotes: 1

Views: 88

Answers (2)

Mark Smith
Mark Smith

Reputation: 71

Node* node;

You define a pointer, but the pointer points to nothing.

Node* node =new Node

You define a pointer and a Node object, and make the pointer point to the object.

Upvotes: 3

Sahil Garg
Sahil Garg

Reputation: 167

Node* node

this is a pointer which is just declared.

Accessing this pointer may give your garbage.

If you want to make pointer point to your own node object, you do by

  1. creating new node object
  2. assign a pointer to it so that you can reference this node later in code using the node pointer like this Node* node = new Node;

Hope this clears!

Upvotes: 0

Related Questions