c++ 结构指针在初始化为 NULL 时无法读取内存
c++ Struct pointer unable to read memory when initialised as NULL
我正在创建一个包含二叉搜索树算法的程序,但我遇到了一个不确定如何解决的问题。这是我代码的相关部分。
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;
};
相关文章:
- 我可以在没有任何锁的情况下从不同的线程读取内存缓冲区吗?
- SAP Netweaver.C++ 错误:无法读取内存
- c++ 结构指针在初始化为 NULL 时无法读取内存
- GDB Python模块读取内存内容
- 内存池和<无法读取内存>
- 读取内存值(实时)最佳实践
- C++无法读取内存地址
- 构造函数问题<无法读取内存>
- C 螺纹池具有共享仅读取内存
- C++ 读取内存地址/指针和偏移量
- C++字符串无法读取内存
- 调用函数时,c++无法使用自定义类读取内存
- 无法读取内存以删除对象数组
- ConstantStruct或ConstantArray读取内存内容
- 如何在可视C++中读取内存地址
- C++:从注入的DLL读取内存的好方法是什么?
- C++ 对象的实例无法读取内存
- <无法读取内存> c++
- 内核驱动程序读取内存未发送整个字符串
- 在C++中嵌入 Python 的错误:无法读取内存