当我们把一个指针作为一个参数传递给函数时,其实是把指针的copy传递给了函数,也可以说传递指针是指针的值传递。
如果我们在函数内部修改指针,修改的只是指针的copy而不是指针本身。代码验证如下:
#include<iostream>
using namespace std;
int num1 = 1;
void func(int* p)
{
p = &num1;
cout << p << endl;
cout << *p << endl;
}
int main()
{
int num2 = 2;
int *p = &num2;
cout << p << endl;
cout << *p << endl;
func(p);
cout << p << endl;
cout << *p << endl;
return 0;
}
指针的指针
#include<iostream>
using namespace std;
int num1 = 1;
void func(int** p)
{
<span style="white-space:pre"> </span>*p = &num1;
<span style="white-space:pre"> </span>**p = 5;
<span style="white-space:pre"> </span>cout << p << ' ' << *p << ' ' << **p << ' ' << num1 << endl;
}
int main()
{
<span style="white-space:pre"> </span>int num2 = 2;
<span style="white-space:pre"> </span>int *pnum2 = &num2;
<span style="white-space:pre"> </span>cout << pnum2 << ' ' << *pnum2 << endl;
<span style="white-space:pre"> </span>func(&pnum2);
<span style="white-space:pre"> </span>cout << pnum2 << ' ' << *pnum2 << endl;
<span style="white-space:pre"> </span>return 0;
}
在函数func中:
p是一个指针的指针
*p是被指向的指针,我们修改它,修改的是被指向的指针的内容,即main函数中的指针p
**p两次解引用是指向main函数的*p的内容
指针的引用
#include<iostream>
using namespace std;
int num1 = 1;
void func(int* &p)
{
p = &num1;
*p = 5;
cout << p << ' ' << *p << ' ' << num1 << endl;
}
int main()
{
int num2 = 2;
int *pnum2 = &num2;
cout << pnum2 << ' ' << *pnum2 << endl;
func(pnum2);
cout << pnum2 << ' ' << *pnum2 << endl;
return 0;
}
在func函数中:
p是指针的引用,即main函数里中的pnum2
*p是main函数中pnum2指向的内容