c++指针的引用:

fun(p) 和 func(&p)
如果我们在函数内部修改指正,只是修改了指针的复制,并不能修改指正本身,但是如果用指针的引用,那么就可以起到修改指正的效果

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
int val = 10;
void (int *p){
p = new int;
*p = val;
}

void func2(int *&p){
p = &val;
p = new int;
*p = val;
}

int main(){

int n =2;
int *p1 = &n;
int *p2 = &n;
cout<<p1<<endl;
func1(p1);
cout<<p1<<endl;

cout<<endl;
cout<<p2<<endl;
func2(p2);
cout<<p2<<endl;

}

结果输出为

0x69fee8
0x69fee8

0x69fee8
0x358d0