1

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
BeruboIV
  • 141
  • 9

1 Answers1

2

In your non-constructor version, t.node holds the address of root.

t.node = &root;

In your constructor version, t.node holds the address of temp, which is indeed a temporary. It becomes a dangling pointer once temp no longer exists.

node = &temp;

In order to match your non-constructor version, your constructor needs to take a Node**.

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);
Drew Dormann
  • 59,987
  • 13
  • 123
  • 180