动态分配内存与释放内存中出现的问题

cristly 2007-04-06 10:26:42
#include<iostream>
#include<math.h>
using namespace std;
void main()
{
int i,j,p;
int k=0;
int *mul;
int *res;
int m,n,temp;
cout<<"Please Entere the value of 'n'"<<endl;
cin>>n;
m=1+(int)(n*log10(2));
mul=new int(m);
res=new int(m+1);
cout<<"m="<<m<<endl;
mul[0]=1;
res[0]=0;

for(i=1;i<m;i++)
{
mul[i]=0;
res[i]=0;
}

for(i=0;i<n;i++)
{
for(j=0;j<m;j++)
{
res[k]=mul[j]*2+res[k];

temp=res[k];
k++;
if(res[k-1]>=10)
{
res[k-1]=res[k-1]%10;
res[k]=temp/10;
}
}
for(p=0;p<k;p++)
{
mul[p]=res[p];

res[p]=0;
}
k=0;

}
for(i=m-1;i>=0;i--)
cout<<mul[i];
cout<<endl;
delete [] mul;//加上这一句连结果也没有
delete [] res;//加上这一句同上

}


该程序是想计算2的N次方,用固定数组的时候能得到正确的结果,但用的动态分配内存后就出现问题了,计算2的10次方以前的结果正确,但往后就出现警告,小的还可以有结果,但到到了解到100次方时就连结果都没有了,就只有警告,不知是何原因,请高手们帮忙看看,期待中.....

...全文
399 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
iu_81 2007-04-06
  • 打赏
  • 举报
回复
呵呵
cristly 2007-04-06
  • 打赏
  • 举报
回复
嗯 ,问题真的出在那里,呵,刚学动态分配,在网上找了好多,就是没注意到那里,呵,谢谢,看了我一早上,你一点问题就解决了,因为是新手,没分给你,不过我有了后会补上的....
xiaolh 2007-04-06
  • 打赏
  • 举报
回复
mul=new int(m);
res=new int(m+1);是分配1个int,并且初始化为*mul=m,*res=m+1

================================================================
不过在我电脑上运行没有错误,可能是内存大点


iu_81 2007-04-06
  • 打赏
  • 举报
回复
mul=new int(m);
res=new int(m+1);
===================
mul=new int[m];
res=new int[m+1];
应该这样

3,882

社区成员

发帖
与我相关
我的任务
社区描述
C/C++ 其它技术问题
社区管理员
  • 其它技术问题社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧