首页 > 编程语言 > 详细

C++中局部变量的返回

时间:2019-09-06 16:36:33      阅读:56      评论:0      收藏:0      [点我收藏+]

在写 “根据中序和后序遍历顺序,构建树的问题” 时,原本这只是一个非常简单的问题,但是突然发现一直有错误。代码如下:

 1 node* get_root(int x1, int x2, int y1, int y2) {
 2     if (x2 == x1) {
 3         return NULL;
 4     }
 5     else if (x2 - x1 == 1) {
 6         node n;
 7         n.data= post_order[x1];
 8         return &n;
 9     }
10     else {
11         int tmp_root = x2 - 1; // 根结点在后序遍历的下标;
12         node n;
13         n.data = post_order[tmp_root]; // 根结点的值;
14         int tmp_index=y1;
15         for (; in_order[tmp_index] != post_order[tmp_root]; tmp_index++) {}
16         n.left = get_root(x1,x1+tmp_index-y1,y1,tmp_index);
17         n.right = get_root(x1 + tmp_index - y1,x2-1,tmp_index+1,y2);
18         return &n;
19     }
20 }

 

一直发现缺少某些元素,最后发现,改为下列代码时,正确运行:

 1 node* get_root(int x1, int x2, int y1, int y2) {
 2     if (x2 == x1) {
 3         return NULL;
 4     }
 5     else if (x2 - x1 == 1) {
 6         node* n=new node();
 7         n->data= post_order[x1];
 8         return n;
 9     }
10     else {
11         int tmp_root = x2 - 1; // 根结点在后序遍历的下标;
12         node* n=new node();
13         n->data = post_order[tmp_root]; // 根结点的值;
14         int tmp_index=y1;
15         for (; in_order[tmp_index] != post_order[tmp_root]; tmp_index++) {}
16         n->left = get_root(x1,x1+tmp_index-y1,y1,tmp_index);
17         n->right = get_root(x1 + tmp_index - y1,x2-1,tmp_index+1,y2);
18         return n;
19     }
20 }

 

错误原因在于局部变量的作用域,在错误的情况,我定义的是普通的局部变量,开辟的内存空间位于stack memory,当函数结束的时候,内存空间进行释放,即使值没有变化,也不能访问对应的内存。当函数结束的时候,即使返回该块内存的地址,也无法对元素进行访问。

 

修改之后,因为使用new操作符,所以该变量的内存空间位于heap memory,需要人工自行进行管理,或者等到程序结束自动释放。因此函数结束并不影响变量的使用。

 

C++中局部变量的返回

原文:https://www.cnblogs.com/yy-1046741080/p/11474902.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!