C++ 返回的指针变成垃圾…c++; Node*binTree::insert(向量向量向量,整数索引){ Node*new_Node=&vec[index]; Node*left_leaf=NULL; Node*right_leaf=NULL; 如果(新建节点->左==-1 | |新建节点->右==-1) 返回新的_节点; 如果(c='n') { 根=新的_节点; c='y'; } 索引=新建节点->左侧; 新建节点->左叶=插入(vec,新建节点->左); 索引=新建节点->右侧; 新建节点->右叶=插入(vec,新建节点->右); 返回NULL; };
我的问题是,在执行递归过程之后,当它碰到“returnnewnode”时,返回的值变成了垃圾。我不知道为什么,有任何提示或修复吗?C++ 返回的指针变成垃圾…c++; Node*binTree::insert(向量向量向量,整数索引){ Node*new_Node=&vec[index]; Node*left_leaf=NULL; Node*right_leaf=NULL; 如果(新建节点->左==-1 | |新建节点->右==-1) 返回新的_节点; 如果(c='n') { 根=新的_节点; c='y'; } 索引=新建节点->左侧; 新建节点->左叶=插入(vec,新建节点->左); 索引=新建节点->右侧; 新建节点->右叶=插入(vec,新建节点->右); 返回NULL; };,c++,C++,我的问题是,在执行递归过程之后,当它碰到“returnnewnode”时,返回的值变成了垃圾。我不知道为什么,有任何提示或修复吗?new\u节点正在引用局部变量中的元素(向量作为复制参数传递)。尝试将其作为引用传递。因为您返回指向局部变量的指针。请尝试通过引用传递该向量。您的意思是:“新建节点->左\u叶=插入(vec,新建节点->左);”?我应该传递&vec吗?Node*binTree::insert(vector&vec,int-index)BTW,I是index,不是吗?只是I在您发布的代
new\u节点
正在引用局部变量中的元素(向量作为复制参数传递)。尝试将其作为引用传递。因为您返回指向局部变量的指针。请尝试通过引用传递该向量。您的意思是:“新建节点->左\u叶=插入(vec,新建节点->左);”?我应该传递&vec吗?Node*binTree::insert(vector&vec,int-index)
BTW,I
是index
,不是吗?只是I
在您发布的代码片段中没有定义;)。我已经编辑了您的代码以匹配它。@john是的,向量不是C数组。如果您尝试传递它,它将被复制(因此通常需要通过引用传递向量)。
Node* binTree::insert(vector<Node> vec, int index) {
Node* new_node = &vec[index];
Node* left_leaf=NULL;
Node* right_leaf=NULL;
if (new_node->left == -1 || new_node->right == -1)
return new_node;
if (c == 'n')
{
root = new_node;
c = 'y';
}
index = new_node->left;
new_node->left_leaf = insert(vec, new_node->left);
index = new_node->right;
new_node->right_leaf = insert(vec, new_node->right);
return NULL;
};