指针参数是如何传递内存

来源:互联网 发布:淘宝店招图片大全免费 编辑:程序博客网 时间:2024/05/21 21:46

如果函数的参数是一个指针,不要指望用该指针去申请动态内存.应该改用“指向指针的指针

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);
}

由于“指向指针的指针”这个概念不容易理解,我们可以用函数返回值来传递动态
内存

char *GetMemory3(int num)
{
char *p = (char *)malloc(sizeof(char) * num);
return p;
}

void Test3(void)
{
char *str = NULL;
str = GetMemory3(100);
strcpy(str, "hello");
cout<< str << endl;
free(str);
}

原创粉丝点击