#include <iostream>
using namespace std;
void GetMemory1(char *p,int num)
{
p=(char*)malloc(sizeof(char)*num);
}
void GetMemory2(char **p,int num)
{
*p=(char*)malloc(sizeof(char)*num);
}
char *GetMemory3(int num)
{
char *p=(char*)malloc(sizeof(char)*num);
return p;
}
/*char *GetMemory4(void)
{
char p[]="hello world";
return p;
}
*/
char *GetMemory5(void)
{
char *p="hello world";
return p;
}
int main()
{
char *str1=NULL;
GetMemory1(str1,100);
if(str1!=NULL)
cout<<"the str1 allocate success"<<endl;
char *str2=NULL;
GetMemory2(&str2,100);
if(str2!=NULL)
cout<<"the str2 allocate success"<<endl;
free(str2);
char *str3=NULL;
str3=GetMemory3(100);
if(str3!=NULL)
cout<<"the str3 allocate success"<<endl;
free(str3);
/*char *str4=NULL;
str4=GetMemory4();
if(str4!=NULL)
cout<<"the str4 allocate success"<<endl;
*/
char *str5=NULL;
str5=GetMemory5();
if(str5!=NULL)
cout<<"the str5 allocate success"<<str5<<endl;
return 0;
}
GetMemory1的p是局部变量,不能分配内存,会造成内存的泄露
GetMemory2采用指向指针的指针进行分配内存
GetMemory3 采用返回值的方式实现内存的分配,但分配内存必须用new或malloc进行分配
GetMemory4会进行报错,把数组分配在栈上,为局部变量,不能实现内存的分配
GetMemory5分配的内存在静态存储区,每次调用都会是hello world。