请教有关new int(1024)和new int[1024]的区别

perfervid 2005-11-10 11:24:42
#include <stdio.h>
#include <windows.h>
#include <winbase.h>

int main()
{
int* pint;
int i = 0;
for(i=0; i<1000; i++)
{
pint = new int(1024);
//delete pint;
if(i%100==0)
{
Sleep(1000);
printf("%d\n", i);
}
}
for(i=0; i<1000; i++)
{
pint = new int[1024];
//delete [] pint;
if(i%100==0)
{
Sleep(1000);
printf("%d\n", i);
}
}
return 0;
}

其中第一个循环运行时就刚开始内存变化了一下,后来基本觉察不出内存的变化。
第二个却是稳定的上升。
哪位大侠可以解释一下吗?

谢谢!
...全文
1178 14 打赏 收藏 转发到动态 举报
写回复
用AI写文章
14 条回复
切换为时间正序
请发表友善的回复…
发表回复
megaboy 2005-11-10
  • 打赏
  • 举报
回复
偶也来接,偶要求不多,20分就OK了!
屁屁 2005-11-10
  • 打赏
  • 举报
回复
对搂住的才能表示肯定,然后,皆分 and 接分
lander9999 2005-11-10
  • 打赏
  • 举报
回复
mark
wohow 2005-11-10
  • 打赏
  • 举报
回复
接分
xuzheng318 2005-11-10
  • 打赏
  • 举报
回复
赞一个!
值得学习!
codearts 2005-11-10
  • 打赏
  • 举报
回复
呵呵,即然搂主自已想出来了,俺来接分就是了
steel007 2005-11-10
  • 打赏
  • 举报
回复
赞!
jlxys 2005-11-10
  • 打赏
  • 举报
回复
好悟性
xiaocai0001 2005-11-10
  • 打赏
  • 举报
回复
汗~

自己突然大悟~
力为 2005-11-10
  • 打赏
  • 举报
回复
楼主还真有意思哦
kobefly 2005-11-10
  • 打赏
  • 举报
回复
自问自答


有个性
perfervid 2005-11-10
  • 打赏
  • 举报
回复
明白了,原来pint = new int(1024);就是

分配了一个没有名字的int 类型的对象对象初始值为1024
然后表达式返回对象在内存中的地址
接着这个地址被用来初始化指针对象pint
对于动态分配的内存
惟一的访问方式是通过指针间接地访问
binbin 2005-11-10
  • 打赏
  • 举报
回复
悟性不错,嘿嘿,偶要分。
TombFigure 2005-11-10
  • 打赏
  • 举报
回复
就是啊
楼主快散分吧
再次简化代码,取消串口,直接显示结果,仍然有问题!!

疑问代码如下:
struct _USB_DATA_STRUCT
{
/*
unsigned char command_data[40];//release结果正确
int command_index;
int command_size;
int numofnod;
*/
int command_index;
int command_size;
int numofnod;
unsigned char command_data[40];//release结果错误

void SetData(unsigned char* pdata,int size)
{
if(size>40)
{
AfxMessageBox("数据太大,超范围!");
return;
}
memcpy(command_data,pdata,size);
}
};

void CTestprjDlg::OnButton1()
{
// TODO: Add your control notification handler code here
unsigned char ctem[32];//错误:32,103,104; 正确:105,110

USB_DATA_STRUCT CommandData;//需要填写要发送的数据

ctem[0]=0xee;
ctem[1]=0x01;
memset(ctem+2,0x00,30);

CommandData.SetData(ctem,32);

ShowTest(CommandData.command_data,32);
}

void CTestprjDlg::ShowTest(unsigned char* p,int nlen)
{
CString str = _T("");
for(int i=0;i <32;i++)
{
CString tmp_str;
tmp_str.Format("0x%02X ", p[i]);
str += tmp_str;
}
m_textctrl.SetWindowText(str);
}

//VC6

Debug版本没有问题,输出如:
EE 01 00 00 00...后面全0
Release版本(按Maximize speed优化)有问题,输出如:
EE 01 00 00 00 00 00 00 00 00 00 00 EE 01 00 00 00 00 00 00 00 00 00 00 EE 01 00 00 00 00 00 00

Release版本下,按以下修改没有问题。
1.调整ctem的大小。小于等于104有问题,大于等于105没有问题。
2.将ctem改为char* ctem;
ctem=new char[32];
没有问题。

3.优化方式由Maximize speed修改为Minimize code也没问题。

请教可能是什么原因?

64,631

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

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