http://topic.csdn.net/u/20080529/16/d408b4ce-32f5-486a-af22-5e40f592696a.html
void CDlgTestDlg::OnButton1() { TCHAR* arr="1"; test(arr); MessageBox(arr); //弹出1 } void CDlgTestDlg::test(TCHAR* pChar) { pChar="2"; //这里修改了值 MessageBox(pChar); //弹出2,已经修改了值,它传递的是地址啊,为什么上面还是弹出1呢? }
我做一些测试。
代码一:
1: #include "stdafx.h"
2: #include <iostream>
3: using namespace std;
4: void Test(char* p)
5: {
6: cout<<"in TEST function scope"<<endl;
7: p = "test";
8: cout<<"p address: "<< &p <<endl;
9: cout<<"p point value : "<<p<<endl;
10: }
11:
12: int _tmain(int argc, _TCHAR* argv[])
13: {
14: char* p ="1";
15:
16: cout<<"p address: "<< &p <<endl;
17: cout<<"p point value : "<<p<<endl;
18:
19: cout<<"run test function"<<endl;
20:
21: Test(p);
22:
23: cout<<"out test scope"<<endl;
24:
25: cout<<"p address: "<< &p <<endl;
26: cout<<"p point value : "<<p<<endl;
27:
28:
29:
30: int i;
31: cin>>i;
32: return 0;
33: }
结果是这样的:
p address: 0012FF60
p point value : 1
run test function
in TEST function scope
p address: 0012FE80
p point value : test
out test scope
p address: 0012FF60
p point value : 1
跟发帖人的情况一样.
来看test函数
1: void Test(char* p)
2: {
3: cout<<"in TEST function scope"<<endl;
4: p = "test";
5: cout<<"p address: "<< &p <<endl;
6: cout<<"p point value : "<<p<<endl;
7: }
在函数test域中,p指针已经是有新的地址 - 0012FE80,并且指向的值是test
经过test后,p指针在_tmain 域中仍然没有变,地址是0012FF60, 指向值是1
代码二:仅仅+入一个符号 &
1: void Test(char* &p)
2: {
3: cout<<"in TEST function scope"<<endl;
4: cout<<"p point original value : "<<p<<endl;
5: p = "test";
6: cout<<"p address: "<< &p <<endl;
7: cout<<"p point value : "<<p<<endl;
8: }
结果就不一样了。
p address: 0012FF60
p point value : 1
run test function
in TEST function scope
p point original value : 1
p address: 0012FF60
p point value : test
out test scope
p address: 0012FF60
p point value : test
通过引用符,传递的是一个引用指针,而不用再复制一个新的指针。因此,还是原来的指针。