The first code works as expected. I am trying to work with double pointers inside structures.
#include "bits/stdc++.h"
using namespace std;
struct Node{
int data;
Node *left;
Node* right;
Node(int val) {
data = val;
left = right = NULL;
}
};
struct Triplet{
Node** node;
int pval, lchild;
};
int main()
{
Node *root = new Node(10);
Triplet t;
t.node = &root;
t.pval = 1001;
t.lchild = 2;
cout << (*t.node)->data << " " << t.pval << " " << t.lchild << "\n";
cout << (*t.node)->data << " " << t.pval << " " << t.lchild << "\n";
cout << (*t.node)->data << " " << t.pval << " " << t.lchild << "\n";
return 0;
}
Below is the correct and expected output
10 1001 2
10 1001 2
10 1001 2
But when I try to use the same logic but with constructor, then I get random values after the first cout
is called. This is not limited to cout
but rather if the double-pointer is accessed once, it will change for the next calls.
#include "bits/stdc++.h"
using namespace std;
struct Node{
int data;
Node *left;
Node* right;
Node(int val) {
data = val;
left = right = NULL;
}
};
struct Triplet{
Node** node;
int pval, lchild;
Triplet(){}
Triplet(Node* temp, int a, int b){
node = &temp;
pval = a;
lchild = b;
}
};
int main()
{
Node *root = new Node(10);
Triplet t(root, 1001, 2);
cout << (*t.node)->data << " " << t.pval << " " << t.lchild << "\n";
cout << (*t.node)->data << " " << t.pval << " " << t.lchild << "\n";
cout << (*t.node)->data << " " << t.pval << " " << t.lchild << "\n";
return 0;
}
Unusual output :
10 1001 2
1878374340 1001 2
1878374340 1001 2