64,684
社区成员
发帖
与我相关
我的任务
分享
#include<iostream>
#include<string>
using namespace std;
struct candy
{
string brand;
double weight;
int calory;
};
int main()
{
candy *snack=new candy[3];
snack[0].brand="Macho Munch";
snack[0].weight=2.3;
snack[0].calory=350;
snack[1].brand="Macho Munch";
snack[1].weight=2.3;
snack[1].calory=350;
snack[2].brand="Macho Munch";
snack[2].weight=2.3;
snack[2].calory=350;
for(int i=0;i<3;i++)
{
cout<<snack[i].brand<<endl;
cout<<snack[i].weight<<endl;
cout<<snack[i].calory<<endl;
};
delete []snack;
system("pause");
return 0;
}
为什么如果不加[ ],就会出现debug assertion failed
candy *snack=new candy[3]; //分配了一组(3个)candy对象的内存空间
构造了3个candy对象,如果用 delete snack,只析构了一个对象candy[0],另外两个没有析构。
这种情况下编译器会检测出错误,并给出“debug assertion failed”或“堆被损坏”的错误信息。