我在下面有两个结构描述。设置huffmanTree = tempNode
后,huffmanTree
的左右内部指针为NULL。但是,在此之前,该值仍然有效,但在设置两个结构彼此相等之后,该值消失了。我做错了什么?
我只是想创建一个huffmanTree struct
并用一些数据初始化它。然后创建一个tempNode
,HuffmanTree *left
指向huffmanTree
,HuffmanTree *right
指向新数据。当我从huffmanTree
打印出数据时,它是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
}
答案 0 :(得分:2)
您执行tempNode.left = &huffmanTree;
,之后huffmanTree = tempNode;
。如果某事没有出错......那将是一个奇迹......
严肃地说,在转让之前:
huffmanTree is { new, new }
tempNode is { &huffmanTree, new }
分配后,huffmanTree is { &huffmanTree, new }
所以你的指针跳跃本质上是:
huffmanTree->huffmanTree->huffmanTree->huffmanLeaf.GetData();
由于你没有为&#34; huffmanTree&#34;定义任何huffmanLeaf,它会返回默认情况下的任何值(未定义的行为,因为你没有初始化data
in你应该的构造函数)