tuyenle tuyenle - 1 year ago 130
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
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
HuffmanTree *left
point to
HuffmanTree *right
point to new data. When I print out the data from
, it was NULL

// Leaf node
typedef struct HuffmanLeaf {
char data;
int count;
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;

// 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 Source

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:


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 )

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download