二进制搜索树插入函数中可能未初始化的本地指针变量

时间:2014-04-29 03:10:01

标签: c++ pointers initialization binary-search-tree

我收到关于指针变量跟踪电流可能未初始化的错误,我对它发生的原因感到有些困惑。

这是我遇到问题的插入函数(错误指向最后一个if语句)

template <class elemType>
void bSearchTreeType<elemType>::addCustomer(const elemType& insertItem)
{
    binaryTreeNode<elemType> *current;  //pointer to traverse the tree
    binaryTreeNode<elemType> *trailCurrent; //pointer behind current
    binaryTreeNode<elemType> *newNode;  //pointer to create the node

    newNode = new binaryTreeNode<elemType>;
    assert(newNode != NULL);
    newNode->info = insertItem;
    newNode->llink = NULL;
    newNode->rlink = NULL;

    if (root == NULL)
        root = newNode;
    else
    {
        current = root;

        while (current != NULL)
        {
            trailCurrent = current;

            if (current->info == insertItem)
            {
                cerr << "The insert item is already in the list-";
                cerr << "duplicates are not allowed."
                    << insertItem << endl;
                return;
            }
            else if (current->info > insertItem)
                current = current->llink;
            else
                current = current->rlink;
        }//end while

        if (trailCurrent->info > insertItem)
            trailCurrent->llink = newNode;
        else
            trailCurrent->rlink = newNode;
    }
}//end insert

1 个答案:

答案 0 :(得分:0)

我很确定这只是编译器感到困惑。显然,如果root为NULL,则它根本不会通过带有while循环的else部分,如果root不是NULL,那么trailCurrent将始终设置为必须的至少进行一次循环。

如果是我,我会在我确定警告不正确时将trailCurrent初始化为root(或NULL)。