#include <bits/stdc .h>
using namespace std;
class node{
public:
int data;
vector<node*> children;
};
node* createTree(const vector<int>& nums){
stack<node*> st;
node *root = new node(nums[0]);
st.push(root);
for(int i=1;i<nums.size();i ){
if(nums[i]==-1){
st.pop();
}else{
node *n = new node(nums[i]);
st.top()->children.push_back(n);
st.push(n);
}
}
return root;
}
void display(node& *root){
cout << root->data << "->";
for(node& *child:root->children)
cout << child->data << " ";
cout <<"\n";
for(node& *child:root->children)
display(child);
}
int main(){
#ifndef ONLINE_JUDGE
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
freopen("error.txt","w",stderr);
#endif
vector<int> nums = {10,20,-1,30,50,-1,60,-1,-1,4,-1,-1};
node *root = createTree(nums);
display(root);
return 0;
}
<source>:25:20: error: 'root' declared as a pointer to a reference of type 'node &'
void display(node& *root){
^
<source>:27:15: error: 'child' declared as a pointer to a reference of type 'node &'
for(node& *child:root->children)
^
<source>:30:15: error: 'child' declared as a pointer to a reference of type 'node &'
for(node& *child:root->children)
^
Here i am trying to implement a generic tree and when i try to compile the program i get an an error message saying that in display function i cannot declare a pointer to node&
. I know that we cannot create a pointer to a reference since references do not have separate physical address, for example something like int* &b
would not be permissible but int& *b
would be permissible.Since here i have used node& *
, i should not have got any error.Then why the program above is giving error?
CodePudding user response:
You're correct about the pointer to a reference vs reference to a pointer but got the syntax wrong.
Pointer to a reference is declared as: type&* obj
Reference to a pointer is declared as: type*& obj
Thus, the way that you think is "wrong", turns out to be correct:
void display(node*& root)
Edit: It's easier to imagine this way: (type*)& obj
vs (type&)* obj