gpt4 book ai didi

c++ - C++中的奇怪指针

转载 作者:行者123 更新时间:2023-11-27 23:48:11 25 4
gpt4 key购买 nike

什么会导致指针在 C++ 中看起来像这样?我正在为项目构建霍夫曼树,当这是当前节点的子节点之一时,我的程序出现段错误。这也不会被 childNode == NULL 检测到。

(TreeNode *) 0x3130303030313131

编辑,以下函数按以下顺序调用:buildTree() -> generateCodes()

void HuffTree::buildTree(MinHeap * heap) {
while (heap->getSize() > 1) {
TreeNode * n1 = heap->removeMin();
TreeNode * n2 = heap->removeMin();

TreeNode * p = new TreeNode(0, (n1 != NULL ? n1->getFrequency() : 0) + (n2 != NULL ? n2->getFrequency() : 0));
p->join(n1, n2);

heap->insert(p);
}

root = heap->removeMin();
}

void HuffTree::generateCodesRecursive(TreeNode * node, int right, string code) {
if (node == NULL) return;

if (node->isLeafNode()) {
codes[node->getVal()] = code;
cout << (unsigned int) node->getVal() << " " << (int) node->getFrequency() << " " << code << endl;
}

generateCodesRecursive(node->getLeft(), 0, code + "1");
generateCodesRecursive(node->getRight(), 0, code + "0");
}

void HuffTree::generateCodes() {
generateCodesRecursive(root, 0, "");
}

编辑,堆函数:

void MinHeap::insert(TreeNode * val) {
nodes.push_back(val);

int index = nodes.size() -1 ;
while (nodes[parent(index)]->getFrequency() > nodes[index]->getFrequency()){
swapNodes(index, parent(index));
index = parent(index);
}
}

TreeNode * MinHeap::removeMin() {
if (nodes.size() == 0) return NULL;

TreeNode* minNode = nodes[0];

if (nodes.size() > 0){
TreeNode* lastNode = nodes[nodes.size()-1];
nodes.pop_back();
nodes[0] = lastNode;
}

int index = 0;
while((left(index) < nodes.size() && nodes[left(index)]->getFrequency() < nodes[index]->getFrequency()) ||
(right(index) < nodes.size() && nodes[right(index)]->getFrequency() < nodes[index]->getFrequency())) {
int swapIndex = right(index) >= nodes.size() ? left(index) : (nodes[left(index)]->getFrequency() <= nodes[right(index)]->getFrequency() ? left(index) : right(index));

swapNodes(swapIndex, index);
index = swapIndex;
}

return minNode;
}

最佳答案

要记住几件事。当您执行 TreeNode* p; 时,p 不会为 null 并将指向垃圾内存,if (p == NULL )if (p == nullptr) 条件,除非您在初始化期间明确将其设置为 null

此外,您是否在其构造函数中正确初始化了 TreeNode 的内部数据成员?

关于c++ - C++中的奇怪指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48877638/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com