错误方法:
void GetMemory(char *str, int size)
{
char * p = (char *)malloc(size);
str = p;
}
int main()
{
char *pstr = NULL;
GetMemory(pstr, 20);
strcpy(pstr, "Hello world");
return 0;
}
正确方法:
char * GetMemory(int size)
{
char * p = (char *)malloc(size);
return p;
}
int main()
{
char *pstr = NULL;
pstr = GetMemory(20);
strcpy(pstr, "Hello world");
return 0;
}
还有一个方法就是使用二级指针
void GetMemory(char **str, int size)
{
char * p = (char *)malloc(size);
*str = p;
}
该方法就想局部变量无法作为出参数。