霍夫曼解码中的递归函数不退出

Recursive function in Huffman Decoding not exiting

本文关键字:退出 递归函数 解码 霍夫曼      更新时间:2023-10-16

我在创建霍夫曼解码功能时遇到了一些麻烦。我只是想知道是否有人知道为什么我的程序会产生无限循环。下面是我的函数以及我是如何计算它的。当计数器命中 8 时,它应该退出函数,因为没有更多的位要读取。在这里:

HuffmanNode *rodee = createTree(freqArray2, 256); //holds the huffman tree
HuffmanNode *temporaryNode; //temporary node for traversing
temporaryNode = rodee; //first the temporary node is equal to the root
while(cin.read((char*)&w, sizeof(w))
{
  traverseCode(temporaryNode, rodee, bits, count);
  count = 0; //reset the count back to 0 for the next time the function is called 
} //as I read in a byte of 8 bits (I converted the bytes to bits in another function not shown
void traverseCode(HuffmanNode *temp, HuffmanNode *root, unsigned char *bits, int counter)
{
    if(counter >= 7)
    {
      counter = 0;
      return; 
    }
    if(temp->getLeft() == NULL && temp->getRight() == NULL)
    {
      cout << temp->getLetter();
      temp = root; 

      traverseCode(temp, root, bits, counter);
    }
    if((int)bits[counter] == 0)
    {
      traverseCode(temp->getLeft(), root,  bits, counter++);
    }
    if((int)bits[counter] == 1)
    {
      traverseCode(temp->getRight(), root, bits, counter++);
    }
}

有谁知道为什么我的函数会进入无限循环以及如何解决这个问题?谢谢!

如果您希望计数器由 traverseCode() 函数更新,它需要是一个引用或指针。在您的代码中,它只是一个局部变量,在函数退出时被丢弃。

所以这什么也没做,除了返回:

if(counter >= 7)
{
  counter = 0;
  return; 
}

接下来的一点也令人困惑。它将调用具有原始值"counter"的函数,这很可能是无限循环的来源。如果它确实返回,它将增加计数器的本地值,然后下降到下一个 if(),这也可能是无意的。

if((int)bits[counter] == 0)
{
  traverseCode(temp->getLeft(), root,  bits, counter++);
}
if((int)bits[counter] == 1)
{
  traverseCode(temp->getRight(), root, bits, counter++);
}

因此,您可能需要以完全不同的方式处理计数器,并且不要让您的 if() 语句像那样失败。