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

c++ Struct pointer unable to read memory when initialised as NULL

本文关键字:读取 内存 NULL 结构 指针 初始化 c++      更新时间:2023-10-16

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

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!";
    }
}

问题就在那里,程序永远不会进入if(ptr->left != NULL(语句。查看我的视觉工作室调试器,ptr->left 显示"而不是 NULL。我该如何解决这个问题!?我在这里尝试了其他一些解决方案,但它们要么不相关,要么不起作用!!

程序永远不会进入 if(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 的回答显示了此函数的更好设计,但您确实需要在容器类级别修复它(,但这是直接的障碍。

你的函数实现整体上没有意义。

函数可以通过以下方式定义

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 );
    }
} 

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

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