0
我有兩個結構如下所述。在設置了huffmanTree = tempNode
之後,huffmanTree
的左右內部指針爲NULL。但是,在此之前,該值仍然有效,但在設置兩個結構相等後,該值就消失了。我究竟做錯了什麼?設置兩個相等的結構後指針爲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
}
可以顯示HummanTree :: left的類型,HuffmanTree的析構函數和任何複製構造函數/賦值運算符的內容?順便說一句,快速修復將是製作huffmanTree和tempNode指針。 – dseifert
它工作。你能告訴我爲什麼嗎? – tuyenle