动态分配内存

内存分配的问题对于程序来说是致命的,对程序员来说是纠结的。

然而内存分配的方式、规则、错误有时候很复杂,有时候又很简单。

 

下面是在子函数中分配内存的几种方式

第一种:出现内存错误的

#include <iostream>
using namespace std;
int *getMemory(int &value,int *ptr)//
{
ptr = new int(value);
return ptr;
}
void main()
{
int number = 100;
int *tptr;
getMemory(number,tptr);
cout<<tptr<<"\n"<<*tptr<<endl;
}
//出错


#include <iostream>
using namespace std;
int *getMemory(int &value)
{
// return new int(value);

int *ptr = new int(value);
return ptr;
}
void main()
{
int number = 100;
int *tptr = getMemory(number);
cout<<getMemory(number)
<<"\n"<<tptr<<"\n"<<*tptr<<endl;
}
//正确

 

#include <iostream>
using namespace std;
int *getMemory(int &value,int *&ptr)
{
// return new int(value);

ptr = new int(value);
return ptr;
}
void main()
{
int number = 100;
int *tptr = 0;
getMemory(number,tptr);
cout<<"\ngetMemory
(number,tptr):"<<getMemory(number,tptr)
<<"\ntptr:"<<tptr
<<"\n*tptr:"<<*tptr<<endl;
}
//正确


#include <iostream>
using namespace std;
int *getMemory(int &value,int **ptr)
{
*ptr = new int(value);
return *ptr;
}
void main()
{
int number = 100;
int *ptr =0;
int **tptr = &ptr;
getMemory(number,tptr);
cout<<"\ntptr:"<<tptr
<<"\n*tptr:"<<*tptr<<"\tptr(tptr
= &ptr):"<<ptr
<<"\n**tptr:"<<**tptr<<endl;
}
//正确

 

 

 

总结:

上面长长的代码是我以前为了弄清楚指针所做的各种测试,

抛开这些难看的参差不齐的代码,我所得到的结论是:

函数统过return总能返回一个地址,但是不能利用形参来返回一个地址,因为形参是实参另一个副本,随着函数调用完毕而自动消失

如果出现了什么让你感觉糊涂的内存错误 (例如运行程序的时候 IDE调用abort()来中断程序)

那肯定是因为指针在使用之前没有初始化,(试问怎么有人舍得糟蹋没有初始化的指针呢? like a virgin of Pointer)

以至程序没法通过编译 或者运行出错。

例如:

#include <iostream>

using std::cout;

int * getNew(int * ptr)

{  ptr = new int(999);

 return ptr; }

int  main()

 {  int *ptr1 = 0, *ptr2 = 0;  

ptr1 = getNew(ptr2);  

 if(ptr1)   {    cout<<*ptr1<<'\n';   }   else   {    cout<<"ptr1 == NULL\n";   }

  if(ptr2)   {    cout<<*ptr2<<'\n';   }   else   {        cout<<"ptr2 == NULL\n";   }

 return 0; }

 

output:

999

ptr2 == NULL

Press any key to continue

 

 

then we know evething,thats to say, error do not appear in getNew()  but main();

 

转载于:https://www.cnblogs.com/Kelvinshere/archive/2012/03/20/2300947.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值