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呢? }

我做一些测试。

代码一:

#include <iostream>
namespace std;
char* p)
   5: {
<<endl;
;
<< &p <<endl;
<<p<<endl;
  10: }
  11:  
int argc, _TCHAR* argv[])
  13: {
;
  15:  
<< &p <<endl;
<<p<<endl;
  18:  
<<endl;
  20:     
  21:     Test(p);
  22:  
<<endl;
  24:  
<< &p <<endl;
<<p<<endl;
  27:  
  28:     
  29:  
int i;
  31:     cin>>i;
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函数

char* p)
   2: {
<<endl;
;
<< &p <<endl;
<<p<<endl;
   7: }

在函数test域中,p指针已经是有新的地址 - 0012FE80,并且指向的值是test

 

经过test后,p指针在_tmain 域中仍然没有变,地址是0012FF60, 指向值是1

 

代码二:仅仅+入一个符号 &

char* &p)
   2: {
<<endl;
<<p<<endl;
;
<< &p <<endl;
<<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

 

通过引用符,传递的是一个引用指针,而不用再复制一个新的指针。因此,还是原来的指针。

相关文章:

  • 2021-06-16
  • 2022-02-12
  • 2022-01-25
  • 2022-12-23
  • 2021-08-17
  • 2022-12-23
  • 2021-09-30
  • 2021-08-23
猜你喜欢
  • 2021-07-15
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-06-29
  • 2021-10-11
相关资源
相似解决方案