tuyenle tuyenle - 22 days ago 8
C++ Question

pointer is NULL after setting two struct equal each other

I have two struct describe below. After setting

huffmanTree = tempNode
, the internal pointer right and left of
huffmanTree
are NULL. However, before that the value was still valid but after setting two struct equal each other the value disappeared. What am I doing wrong?

I just want to create a
huffmanTree struct
and initialize it with some data. Then create a
tempNode
having
HuffmanTree *left
point to
huffmanTree
and
HuffmanTree *right
point to new data. When I print out the data from
huffmanTree
, it was NULL

// Leaf node
typedef struct HuffmanLeaf {
private:
char data;
int count;
public:
HuffmanLeaf() {

}

void setData(char data) {
this->data = data;
}

void setCount(int count) {
this->count = count;
}

char getData() {
return this->data;
}

int getCount() {
return this->count;
}
}HuffmanLeaf;


// Huffman tree
typedef struct HuffmanTree {
HuffmanTree *right;
HuffmanTree *left;
HuffmanLeaf huffmanLeaf;
} HuffmanTree;

int main() {
/* huffmanLeaf[] was defined and initialized
.
.
.
.
*/

// Take the first two smallest and so on
HuffmanTree huffmanTree;
HuffmanTree tempNode;

// Allocate memory for internal struct
huffmanTree.left = new (HuffmanTree);
huffmanTree.right = new (HuffmanTree);
tempNode.left = new (HuffmanTree);
tempNode.right = new (HuffmanTree);

// Two character with least frequency. Create a new Tree
huffmanTree.right->huffmanLeaf = huffmanLeaf[0];
huffmanTree.left->huffmanLeaf = huffmanLeaf[1];


// Next character
tempNode.left = &huffmanTree; // have node left point to huffmanTree
tempNode.right->huffmanLeaf = huffmanLeaf[2]; // new data on node right

/* Data is still here for tempNode */
cout << tempNode.left->left->huffmanLeaf.getData() << endl;

/* Error occured after this */
huffmanTree = tempNode;

// Value is NULL
cout << huffmanTree.left->left->huffmanLeaf.getData() << endl; // Value is NULL
}

Answer

You do tempNode.left = &huffmanTree;, and after that huffmanTree = tempNode;. It would be a miracle if something didn't go wrong...

Seriously though, before assignment:

huffmanTree is { new, new }
tempNode is { &huffmanTree, new }

After the assignment, huffmanTree is { &huffmanTree, new }

So your pointer jumping is essentially:

huffmanTree->huffmanTree->huffmanTree->huffmanLeaf.GetData();

and since you hadn't defined any huffmanLeaf for "huffmanTree", it returns any value it had by default( undefined behavior, since you don't initialize data in the constructor as you should )