首页 新闻 会员 周边

函数参数为指针的值传递与引用传递

0
[待解决问题]

1.问题的由来:今天在实现二叉树的创建和遍历的时候,发现在(二叉树的建立的参数的)代码中少了一个引用符号,然后编译器会报错:”使用了未初始化的局部变量“,在我使用了引用之后,便没有了这样的错误。

2.给出代码

 1 #include<iostream>
 2 using namespace std;
 3 
 4 typedef char element_type; //declare that element's type is char
 5 typedef struct Bnode {
 6     element_type data;
 7     struct Bnode *Lson, *Rson;
 8 } Bnode, *Bptr;
 9 //create a prologue Btree
10 int createBtree(Bptr &T) {
11     char data;
12     cin >> data;
13     if (data == '#') {
14         T = NULL;
15     }
16     else {
17         T = new Bnode();//assign the space for the root
18         T->data = data;
19         createBtree(T->Lson);
20         createBtree(T->Rson);
21     }
22     return 0;
23 }
24 void visit(Bptr T) {
25     if (T->data != '#') {
26         cout << T->data;
27     }
28 }
29 void inorder(Bptr p) { //p points to the root of the Btree
30     if (p == NULL) return;
31     inorder(p->Lson);
32     visit(p);
33     inorder(p->Rson);
34 }
35 void postorder(Bptr p) { //p points to the root of the Btree
36     if (p == NULL) return;
37     postorder(p->Lson);
38     postorder(p->Rson);
39     visit(p);
40 }
41 int main()
42 {
43     Bptr T;
44     cout << "输入字符串,建立二叉树: ";
45     createBtree(T);
46     cout << "二叉树的中序遍历: ";
47     inorder(T);
48     cout << endl;
49     cout << "二叉树的后序遍历: ";
50     postorder(T);
51     cout << endl;
52     system("pause");
53 }

3.问题出在第10行。

4.做过了哪些尝试:

(1)把43行改为:Bptr T=NULL。结果编译成功了,但是没有实现功能

5.疑问:为什么要用引用? 为什么遍历函数不用引用就没事,而构建二叉树必须要引用参数呢?

MarkKobs的主页 MarkKobs | 菜鸟二级 | 园豆:202
提问于:2016-12-22 19:46
< >
分享
所有回答(2)
0

43 Bptr T; 44 cout << "输入字符串,建立二叉树: "; 45 createBtree(T);

你的想法应该是通过createBtree构建出来T这个变量,如果不加引用,那么

这个类型是指针类型,透过函数传递时,传递的是其值,这个值由于没有初始化值,是内存的一个随机值

createBtree函数里面把T的值给改了,这个是函数局部的,修改传递不出去,因此外部没法用

2012 | 园豆:21230 (高人七级) | 2016-12-25 17:46
0

专家说的对啊

Dmego | 园豆:246 (菜鸟二级) | 2016-12-29 21:56
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册