2016-11-16 65 views
0

我有兩個結構如下所述。在設置了huffmanTree = tempNode之後,huffmanTree的左右內部指針爲NULL。但是,在此之前,該值仍然有效,但在設置兩個結構相等後,該值就消失了。我究竟做錯了什麼?設置兩個相等的結構後指針爲NULL

我只是想創建一個huffmanTree struct並用一些數據初始化它。然後創建一個tempNode,其中HuffmanTree *left指向huffmanTreeHuffmanTree *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 
} 
+2

可以顯示HummanTree :: left的類型,HuffmanTree的析構函數和任何複製構造函數/賦值運算符的內容?順便說一句,快速修復將是製作huffmanTree和tempNode指針。 – dseifert

+0

它工作。你能告訴我爲什麼嗎? – tuyenle

回答

2

你做tempNode.left = &huffmanTree;,那huffmanTree = tempNode;後。這將是一個奇蹟,如果事情沒有出問題......

雖然嚴重,分配前:

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

任務後,huffmanTree is { &huffmanTree, new }

所以你的指針跳躍基本上是:

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

由於您沒有爲「huffmanTree」定義任何huffmanLeaf,它將返回任何val它有默認情況下(未定義的行爲,因爲你沒有初始化構造函數中的data

相關問題