malloc在子函数中返回方式 | 您所在的位置:网站首页 › c语言malloc函数返回值 › malloc在子函数中返回方式 |
目录 一、通过函数返回值返回 二、通过二级指针传参 一、通过函数返回值返回通过子函数的返回值返回malloc到的空间的首地址 #include #include #include char* test1() { char *p; p = (char*)malloc(10 * sizeof(char)); strcpy(p, "11111111" ); return p; //此处返回的是申请到的内存空间的首地址 } void main(int argc,const char *argv[]) { char *str = NULL ; str = test1(); printf("%s\n", str); free(str); //一定要释放 不然会出现野指针 return 0; } 二、通过二级指针传参#include #include #include void test2(char **p) //注意这里是二级指针 { *p = (char*)malloc(10 * sizeof(char)); strcpy(*p, "123456789" ); } void main() { char *str = NULL ; test2(&str);//注意这里传的是地址 printf("%s\n", str); free(str);//一定要释放 str = NULL ; } 如果传递的只是str,相当于只是把str的值 而str是指向NULL的,等于把NULL传递了过去,此时char **p= NULL;实际在子函数中确实分配到内存空间给p了,但是这时p和str毫无关系了,这时在子函数中分配的内存空间是无法成功返回到主函数内的,进而无法释放造成内存泄漏。而通过&str传递给子函数test2,此时二级指针p = &str,那么对*p的操作其实就是对str的操作了,这样就可以通过子函数给strmalloc到内存了。 补充:对于形参中定义的 char **p,二级指针p=&str,指向为srt(此时str还是一个指针),一级指针*p = str,而**p = *str; |
CopyRight 2018-2019 实验室设备网 版权所有 |