指针部分一直是难理解的,特意做笔记如下,直接上代码
#include<iostream>
using namespace std;
void swap1(int a,int b);
void swap2(int* p1, int* p2);
void swap3(int* p1, int* p2);
int main() {
int a = 1, b = 2;
cout << "---------------swap1---------------------" << endl;
swap1(a, b);//swap1内的交换不改变外部a和b的值
cout << "swap1 a=" << a << endl;
cout << "swap1 b=" << b << endl;
cout << "---------------swap2---------------------" << endl;
swap2(&a, &b);//swap2内的交换不改变外部a和b的值
cout << "swap2 a=" << a << endl;
cout << "swap2 b=" << b << endl;
cout << "---------------swap3---------------------" << endl;
swap3(&a, &b);
cout << "swap3 a=" << a << endl;
cout << "swap3 b=" << b << endl;
}
void swap1(int a,int b){//值传递,形参不改变实参
int temp = a;
a = b;
b = temp;
cout << "in swap1 a=" << a << endl;
cout << "in swap1 b=" << b << endl;
}
void swap2(int* p1, int* p2) {//指针传递,虽然传递的是指针,但是在交换的是形参指针,实际指向a和b的指针不变
int* p3 = p1;
p1 = p2;
p2 = p3;
cout << "in swap2 a=" << *p1 << endl;
cout << "in swap2 b=" << *p2 << endl;
}
void swap3(int* p1, int* p2) {//指针传递,对传过来的实参的指针进行交换,所以最终在内存中,a和b的指针指向发生了变化
int temp = *p1;
*p1 = *p2;
*p2 = temp;
cout << "in swap3 p1=" << *p1 << endl;
cout << "in swap3 p2=" << *p2 << endl;
}
输出结果:
---------------swap1---------------------
in swap1 a=2
in swap1 b=1
swap1 a=1
swap1 b=2
---------------swap2---------------------
in swap2 a=2
in swap2 b=1
swap2 a=1
swap2 b=2
---------------swap3---------------------
in swap3 p1=2
in swap3 p2=1
swap3 a=2
swap3 b=1
自己创建的两个群,一个是做3D方面的(包括算法图像处理,以及三维模型生成等),另一个是代码编程群,两个群都是为了交流技术的,欢迎加入,禁止发广告。