沒法把指針變量自己傳遞給一個函數的解決方法

//1:傳遞指針的方法無效,結果致使內存泄露
void GetMemory(char *p,int num)
{
    p=(char*)malloc(num*sizeof(char));
}
int main()
{
    char *str=NULL;
    GetMemory(str,10);
    strcpy(str,"hello");
    free(str);//free 並無起做用,內存泄露
    return 0;
}
//2:return 返回分配內存地址
char* GetMemory(char *p,int num)
{
    p=(char*)malloc(num*sizeof(char)
    return p;
}
int main()
{
    char* str=NULL;
    str=GetMemory(str,10);
    strcpy(str,"hello");
    free(str);
    return 0;
}
//3:二級指針的使用,將指針地址傳遞給函數,改變指針內容(即分配內存首地址)
void GetMemory(char **p,int num)
{
    *p=(char*)malloc(num*sizeof(char));
    return p;
}
int main()
{
    char *str=NULL;
    GetMemory(&str,10);
    strcppy(str,"hello");
    free(str);
    return 0;
}
相關文章
相關標籤/搜索