Reputation: 167
This code snippet is valid for creating new node at the begining.
void push(node **head_ref,int n_data){
node *new_node= new(node);
new_node->data=n_data;
new_node->next=(*head_ref);
*head_ref=new_node;
}
int main(){
node *head=NULL;
push(&head,data);
return 0;
}
This is invalid but why? What i am trying to do is create a reference parameter as mentioned in Herbert Schildt.
void push(node &(*head_ref),int n_data){
node *new_node= new(node);
new_node->data=n_data;
new_node->next=head_ref;
head_ref=new_node;
}
int main(){
node *head=NULL;
push(head,data);
return 0;
}
Upvotes: 0
Views: 981
Reputation: 1063
A Null-Pointer can't be a reference! So in C++ there is the only way, to use a double pointer.
Using a Reference to a Null-Pointer could lead to undefined behavior, this means that you should avoid this.
Maybe boost::optional is what you need, but than you need some modifications.
But why are you not just using the std::list?
Upvotes: 0
Reputation: 409186
The declaration node &(*head_ref)
makes head_ref
a pointer to a reference, not a reference to a pointer, which would be node*& head_ref
.
Upvotes: 2