指针参数的传递和内存分配

#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。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值