Raaj - 1 year ago 62

C++ Question

Suppose I have a struct declared like below -

`struct node{`

node *next;

int data;

}

and I have a C++ function in a

`class Stack`

`push`

`void Stack::push(int n){`

node *temp = new node;

temp->data = n;

temp->next = top;

top = temp;

if(topMin == NULL) {

temp = new node;

temp->data = n;

temp->next = topMin;

topMin = temp;

return;

}

if(top->data < topMin->data) {

temp = new node;

temp->data = n;

temp->next = topMin;

topMin = temp;

}

return;

}

What's the difference between using

`node *temp = new node;`

and

`temp = new node;`

in the code above? More specifically, I'm confused about the implication.

If temp is a pointer(*), I understand that

`temp->data`

is just dereferencing the pointer to struct (

`(*temp).data`

what does it mean to be using

`temp = new node`

Is it just a difference of representation?

Answer Source

```
node *temp = new node;
```

is both declaring `temp`

and initializing it, while

```
temp = new node;
```

is assigning to a variable that has already been declared, so the compiler already knows what type it is.