如果要通过函数改变一个指针的值,要往函数中传入指针的指针
如果要通过函数改变一个变量的值,那就要往函数中传入这个变量的地址
改变a的值和b的值
#include <iostream>
using namespace std;
void swap(int* a, int* b) {
int temp = *a;
*a = *b;
*b = temp;
}
int main() {
int a = 10;
int b = 20;
int* pa = &a;
int* pb = &b;
cout << a << endl; // 10
cout << b << endl; // 20
//需要传入a和b的地址
swap(pa,pb);
cout << "-------swap()--------" << endl;
cout << a << endl; // 10
cout << b << endl; // 20
return 0;
}
改变pa的值和pb的值
#include <iostream>
using namespace std;
void changepoint(int** ppa, int** ppb) {
int* temp = *ppa; //*ppa=1000=*1090=*(&pa)=pa
*ppa = *ppb;
*ppb = temp;
}
int main() {
int a = 10;
int b = 20;
int* pa = &a;
int* pb = &b;
cout << *pa << endl; // 10
cout << *pb << endl; // 20
//需要传入pa和pb的地址
changepoint(&pa, &pb);
cout << "-------changepoint()--------" << endl;
cout << *pa << endl; // 10
cout << *pb << endl; // 20
return 0;
}