函数参数为 "char* p" 与 "char*& p" 的区别



  1. #include <iostream>  
  2. using namespace std;  
  3.   
  4. void New(char*& p) //注意:这里的参数不能用"char* p",而必须要用"char*& p"。  
  5. {  
  6.     p = new char[32];  
  7. }  
  8.   
  9. int main(int argc, char* argv[])  
  10. {  
  11.     char* p = NULL;  
  12.     New(p);  
  13.     strcpy(p, "hello"); //"strcpy"只会在有效值之后补个 '\0' ,并不会把所有旧值都清空。  
  14.     printf("%s", p);  
  15.   
  16.     return 0;  
  17. }  
  1. #include <iostream>  
  2. using namespace std;  
  3.   
  4. void New(char*& p) //注意:这里的参数不能用"char* p",而必须要用"char*& p"。  
  5. {  
  6.     p = new char[32];  
  7. }  
  8.   
  9. int main(int argc, char* argv[])  
  10. {  
  11.     char* p = NULL;  
  12.     New(p);  
  13.     strcpy(p, "hello"); //"strcpy"只会在有效值之后补个 '\0' ,并不会把所有旧值都清空。  
  14.     printf("%s", p);  
  15.   
  16.     return 0;  
  17. }  

猜你喜欢

转载自blog.csdn.net/qq_23981335/article/details/69483947