当前位置: 代码迷 >> 综合 >> C语言 指针出参使用方法
  详细解决方案

C语言 指针出参使用方法

热度:41   发布时间:2024-01-20 09:58:13.0

错误方法:
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;
}

该方法就想局部变量无法作为出参数。