C/C++ 内存传递 指针

来源:互联网 发布:安卓ssr软件 编辑:程序博客网 时间:2024/06/04 21:22


程序1:

[cpp] view plaincopy
  1. void getmemory(char *p)  
  2. {   
  3.     p=(char*)malloc(100);  
  4. }  
  5. void test(void)  
  6. {  
  7.    char * str = NULL;  
  8.    getmemory(str);  
  9.    strcpy(str,"hello,world");  
  10.    printf(str);  
  11. }  
  12.   
  13. int main()  
  14. {  
  15.     test();  
  16. }  

程序1运行是会报错的,调用getmemory(str)后,在test函数内的局部变量str并未产生变化, strcpy ( str ,” hello , world ”)  写越界,造成segmentation fault。

要修改以上程序有两个办法,

修改1:  形参由char *p改成char *&p就正确了

[cpp] view plaincopy
  1. void getmemory(char *&p)  
  2. {   
  3.     p=(char*)malloc(100);  
  4. }  
  5. void test(void)  
  6. {  
  7.    char * str = NULL;  
  8.    getmemory(str);  
  9.    strcpy(str,"hello,world");  
  10.    printf(str);  
  11. }  
  12.   
  13. int main()  
  14. {  
  15.     test();  
  16. }  


修改2:传入str的地址,形参改为指向指针的指针

[cpp] view plaincopy
  1. void getmemory(char **p)  
  2. {   
  3.     *p=(char*)malloc(100);  
  4. }  
  5. void test(void)  
  6. {  
  7.    char * str = NULL;  
  8.    getmemory(&str);  
  9.    strcpy(str,"hello,world");  
  10.    printf(str);  
  11. }  
  12.   
  13. int main()  
  14. {  
  15.     test();  
  16. }  
0 0
原创粉丝点击