美文网首页
二级指针传参数

二级指针传参数

作者: lmem | 来源:发表于2017-06-11 17:54 被阅读112次

错误方式申请内存

void GetMemory(char *p, int num)   
{   
     p = (char *)malloc(sizeof(char) * num);   
}   
void Test(void)   
{   
     char *str = NULL;   
     GetMemory(str, 100);  // str 仍然为 NULL   
     strcpy(str, "hello");  // 运行错误   
}  
Paste_Image.png

毛病出在函数 GetMemory中。编译器总是要为函数的每个参数制作临时副本,指针参数 p 的副本是 _p,编译器使 _p =p。如果函数体内的程序修改了_p 的内容,就导致参数 p 的内容作相应的修改。这就是指针可以用作输出参数的原因。在本例中,_p 申请了新的内存,只是把_p 所指的内存地址改变了,但是 p 丝毫未变。所以函数 GetMemory并不能输出任何东西。事实上,每执行一次 GetMemory 就会泄露一块内存,因为没有用free 释放内存。 如果非得要用指针参数去申请内存,那么应该改用“指向指针的指针”

正确方式申请

void GetMemory2(char **p, int num)   
{   
    *p = (char *)malloc(sizeof(char) * num);   
}  
void Test2(void)   
{   
     char *str = NULL;   
     GetMemory2(&str, 100); // 注意参数是 &str,而不是 str   
     strcpy(str, "hello");    
     cout<< str << endl;   
     free(str);    
}   
Paste_Image.png

相关文章

网友评论

      本文标题:二级指针传参数

      本文链接:https://www.haomeiwen.com/subject/cznhqxtx.html