c ++结构指针在初始化为NULL时无法读取内存

时间:2018-03-23 15:05:31

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

我正在创建一个包含二进制搜索树算法的程序,但我遇到了一个我不确定如何解决的问题。下面是我的代码的相关部分。

struct node {
    string data;
    node *left = NULL;
    node *right = NULL;
};

这就是节点的结构。

void Insert_Rec(string word, node* ptr) {

if (ptr->data == "") {

    ptr->data = word;
    ptr->left = NULL;
    ptr->right = NULL;
    cout << "overwitten!" << endl;
}
else if (word < ptr->data) {
    if (ptr->left != NULL) {
        cout << "Recursing left!";
        Insert_Rec(word, ptr->left);
    }
    else {
        ptr->data = word;
        ptr->left = NULL;
        ptr->right = NULL;
        cout << "Inserted!";
    }
}

问题在于,如果(ptr-> left!= NULL)语句,程序永远不会进入。查看我的visual studio调试器,ptr-&gt; left显示“”而不是NULL。我怎么能解决这个问题!?我在这里尝试过其他一些解决方案,但它们要么不相关,要么就是不工作!

3 个答案:

答案 0 :(得分:2)

  如果(ptr->; left!= NULL)语句

程序永远不会进入

ptr->left开始为NULL,你永远不会为它分配任何其他东西,所以它将永远保持为NULL。

if (ptr->left) {
    cout << "Recursing left!";
    Insert_Rec(word, ptr->left);
}
else {
    /* this just overwrites the existing node in-place
       but you should be creating a new node for the left child
    ptr->data = word;
    ptr->left = NULL;
    ptr->right = NULL;
    */
    ptr->left = new node{word, nullptr, nullptr};
    cout << "Inserted!";
}

你的代码还有很多其他问题(Vlad-from-Moscow的回答显示了这个函数的更好的设计,但你真的需要在容器类级别修复它),但这是直接的阻塞。 / p>

答案 1 :(得分:2)

你的功能实现整体上没有意义。

该功能可以通过以下方式定义

void Insert_Rec( node **head, const std::string &word ) 
{
    if ( *head == nullptr )
    {
        *head = new node { word, nullptr, nullptr };
    }
    else if ( word < ( *head )->data )
    {
        Insert_Rec( &( *head )->left, word );
    }
    else
    {
        Insert_Rec( &( *head )->right, word );
    }
}  

如果需要,应该分配新节点的功能。

如果您希望BST不包含重复项,请将最后else语句更改为else if语句,如

else if ( ( *head )->data < word )

可以通过以下方式调用该函数

node *head = nullptr;
//...
Insert_Rec( &head, "Hello" );

也可以使用引用的类型作为第一个函数参数的类型而不是“double”指针。

例如

void Insert_Rec( node * &head, const std::string &word ) 
{
    if ( head == nullptr )
    {
        head = new node { word, nullptr, nullptr };
    }
    else if ( word < head->data )
    {
        Insert_Rec( head->left, word );
    }
    else
    {
        Insert_Rec( head->right, word );
    }
} 

答案 2 :(得分:0)

您在struct中设置了node * left = NULL和node * right = NULL。删除该NULL。只留下两个指针。否则,它只是空。无论如何,请记住,您很少想要初始化结构中的指针。

struct node {
    // simple is better (-:
    string data;
    struct node *left;
    struct node *right;
};