关于结构体的程序崩溃的问题

lbtdmz 2012-11-18 01:57:58
#include<iostream>
#include <string>
using namespace std;
struct inflatable
{

// std::string name;VC6.0 不能对结构体的string进行初始化 在VC2010或者 uinx C++就可以
// 会报错 error C2552: 'hat' : non-aggregates cannot be initialized with initializer list
char name[20];
double volume;
double price;
};

int main()
{
inflatable hat[3]=
{
{"hat",1.52,80.55},
{"book",1.88,15.2},
};

cout<<hat[0].name<<"\t"<<hat[0].volume<<"\t"<<hat[0].price<<endl;
cout<<hat[1].name<<"\t"<<hat[1].volume<<"\t"<<hat[1].price<<endl;
strcpy(hat[3].name,hat[0].name);
hat[3].price=hat[0].price;
hat[3].volume=hat[0].volume;
cout<<hat[3].name<<"\t"<<hat[3].volume<<"\t"<<hat[3].price<<endl;
return 0;
}



运行都有输出但是最后会崩溃 debug到这里会错


...全文
390 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
转角天边 2012-11-18
  • 打赏
  • 举报
回复
引用 1 楼 wingzero520 的回复:
inflatable hat[3] hat数组的有效索引是0到2,strcpy(hat[3].name,hat[0].name); 这句话已越界
楼上正解,数组的下标是从0开始 定义inflatable hat[3]; hat[0],hat[1],hat[2]才是分配的合法空间
lbtdmz 2012-11-18
  • 打赏
  • 举报
回复
额,好吧!确实是这样的,迷糊了。谢谢!
wingzero520 2012-11-18
  • 打赏
  • 举报
回复
inflatable hat[3] hat数组的有效索引是0到2,strcpy(hat[3].name,hat[0].name); 这句话已越界

64,688

社区成员

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

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