[英]Why a struct pointer can't be declared by another struct pointer
今天学习了二叉搜索树,我正在尝试实现它,但是我遇到了一个问题。
假设我有一个这样的Struct
:
struct Node {
int v;
Node* left = NULL;
Node* right = NULL;
}
在它下面,我有:
// At the beginning, root is NULL
Node* root = NULL;
Node* new_node(int v) {
Node* n = new Node;
n->v = v;
return n;
}
void insert(int v) {
// At the beginning, root is NULL
Node* c = root;
while (c != NULL) {
if (v < c->v) {
c = c->left;
} else {
c = c->right;
}
}
c = new_node(v);
}
在主代码中,我使用以下代码测试了我的实现:
int main() {
insert(5);
}
When I use insert(5)
, in insert
function, the variable c
will be root
, and because root
at that time is NULL
, so c
will equal to new_node(v)
. 但是当我打印root->v
时,它什么也不返回。
我是不是做错了什么??
在您的代码中,您不会在初始化后修改root
。 root
始终是NULL
。 这个
Node* c = root;
// ...
c = new_node(v);
不会更改root
。 它只是声明了一个局部变量c
,用root
的值初始化它并为其分配一个新值。
如果您想更改 function 中某些内容的值,您可以通过引用传递它,指针对此没有什么不同。 例如:
#include <iostream>
struct Node {
int v;
Node* left = NULL;
Node* right = NULL;
};
Node* root = NULL;
Node*& find_insertion(Node*& ptr, int v){
if (ptr == NULL) return ptr;
if (v < ptr->v) {
return find_insertion(ptr->left,v);
} else {
return find_insertion(ptr->right,v);
}
}
void insert_at(Node*& ptr,int v){
Node*& insertion = find_insertion(root,v);
insertion = new Node;
insertion->v = v;
}
void insert(int v){
insert_at(root,v);
}
int main() {
insert(5);
std::cout << root->v;
}
接下来,您应该查看智能指针 ( std::unique_ptr
) 以避免泄漏或复杂的手动 memory 管理。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.