引入:
指针传参也只是值传递,只是这个“值”是地址,也就是说当主函数中的 p 作为参数传递时,被调用的函数会生成一个对应指针类型的临时变量作为暂存 p 中的值,这个临时变量的地址与原来 p 的地址不同,也就是说我们改变 tmp_p并不能改变 p 的值。
#include <iostream>
using namespace std;
void PrintAdr(int * p) {
cout << "参数中p的地址:" << &p << endl;
}
int main () {
int a = 250;
int * p = &a;
cout << "原p的地址:" << &p << endl;
PrintAdr(p);
return 0;
}
练习:
找出下列程序的bug
#include <iostream>
#include <vector>
using namespace std;
typedef struct node {
int info;
struct node * left_child;
struct node * right_child;
}binary_search_tree;
void insert_node(int val, binary_search_tree * T) {
binary_search_tree* newnode = new binary_search_tree;
newnode->info = val;
if (T == NULL) {
T = newnode;
return;
}
if (val < T->info) insert_node(val, T->left_child);
else if (val >= T->info) insert_node(val, T->right_child);
}
void in_traversal(binary_search_tree * T) {
if (T == NULL) return;
in_traversal(T->left_child);
cout << T->info << " ";
in_traversal(T->right_child);
}
int main () {
int n = 7;
binary_search_tree * T = NULL;
for (int i = 1; i <= n; i++)
insert_node(i, T);
in_traversal(T);
return 0;
}
在函数 insert_node 中,当 T 的值为 NULL 时,T = newnode 只是把 newnode 的值赋值给临时变量 T,而非主函数中的 T ,当函数 insert_node 结束时,临时变量 T 就会被销毁掉。
修改:
#include <iostream>
using namespace std;
void PrintAdr(int * &p) {
cout << "参数中p的地址:" << &p << endl;
}
int main () {
int a = 250;
int * p = &a;
cout << "原p的地址:" << &p << endl;
PrintAdr(p);
return 0;
}
#include <iostream>
using namespace std;
typedef struct node {
int first;
int second;
struct node * next;
}Node;
int main () {
Node *n1 = new Node;
if (n1->next == NULL)
cout << "Yes" << endl;
else cout << "No" << endl;
return 0;
}
在这段代码中,创建了一个名为 Node
的结构体,其中包含了两个整型成员 first
和 second
,以及一个指向结构体自身的指针 next
。在 main
函数中,通过 new
关键字动态分配了一个 Node
类型的对象,并将其地址赋值给 n1
指针。
接着,通过 n1->next
来访问 n1
指针所指向的对象的 next
成员。由于刚刚创建的对象没有被初始化,其中的 next
成员的值是不确定的,可能是一个随机的地址值。
因此,无法确定 n1->next
是否为 NULL
。因此,无法确定输出结果是 "Yes" 还是 "No"。这取决于 n1->next
的值是否为 NULL
。
#include <iostream>
#include <vector>
using namespace std;
typedef struct node {
int info;
struct node * left_child;
struct node * right_child;
}binary_search_tree;
binary_search_tree * create_node(int val) {
binary_search_tree * newnode = new binary_search_tree;
newnode->info = val;
newnode->left_child = NULL;
newnode->right_child = NULL;
return newnode;
}
binary_search_tree * insert_node(int val, binary_search_tree * T) {
if (T == NULL) {
return create_node(val);
}
if (val < T->info) T->left_child = insert_node(val, T->left_child);
else if (val >= T->info) T->right_child = insert_node(val, T->right_child);
return T;
}
void in_traversal(binary_search_tree * T) {
if (T == NULL) return;
in_traversal(T->left_child);
cout << T->info << " ";
in_traversal(T->right_child);
}
int main () {
int n = 7;
binary_search_tree * T = NULL;
//for (int i = 1; i <= n; i++)
//T = insert_node(i, T);
T = insert_node(9, T);
T = insert_node(19, T);
T = insert_node(7, T);
T = insert_node(3, T);
T = insert_node(0, T);
in_traversal(T);
return 0;
}