#图解 轻松看懂「指针的引用*&」 - 知乎 (zhihu.com)

注意“举个栗子”中的第一个代码:(以一个更为简单的例子为例)

情况1:

 1 void swap(int* p1, int* p2) {
 2 
 3     int temp = *p1;
 4     *p1 = *p2;
 5     *p2 = temp;
 6     cout << "交换中:" << endl;
 7     cout << "(值)p1=" << *p1 << endl;
 8     cout << "(值)p2=" << *p2 << endl;
 9        
10 }
11 
12 int main() {
13 
14     int a = 1, b = 3;
15     int* p1 = &a, * p2 = &b;
16 
17     // 交换前
18     cout << "交换前:" << endl;
19     cout << "a=" << a << endl;
20     cout << "b=" << b << endl;
21     // 交换中
22     swap(p1, p2);
23     // 交换后
24     cout << "交换后:" << endl;
25     cout << "a=" << a << endl;
26     cout << "b=" << b << endl;
27     return 0;
28 
29 }

运行结果:

 

* 注意*这是正常的地址传递

情况2:

 1 void swap(int* p1, int* p2) {
 2 
 3     int* temp = p1;
 4     p1 = p2;
 5     p2 = temp;
 6     cout << "交换中:" << endl;
 7     cout << "(值)p1=" << *p1 << endl;
 8     cout << "(值)p2=" << *p2 << endl;
 9        
10 }
11 
12 int main() {
13 
14     int a = 1, b = 3;
15     int* p1 = &a, * p2 = &b;
16 
17     // 交换前
18     cout << "交换前:" << endl;
19     cout << "a=" << a << endl;
20     cout << "b=" << b << endl;
21     // 交换中
22     swap(p1, p2);
23     // 交换后
24     cout << "交换后:" << endl;
25     cout << "a=" << a << endl;
26     cout << "b=" << b << endl;
27     return 0;
28 
29 }

运行结果:

 

 *注意*此例swap函数只是将p1和p2装载的地址进行交换,但没有交换两个地址中具体的值

未完待续。。。。。

posted on 2022-09-26 15:43  小凉拖  阅读(60)  评论(0编辑  收藏  举报