编了一个程序,编译无异常。但是运行时系统报错
编了一个程序,编译无错误。但是运行时系统报错。
小弟编了个程序,:设计一个名为car的结构,用它存储下述有关汽车的信息:生产商、生产年份。编写一个程序,向用户询问有多少量汽车,随后,程序用new来创建一个由相应数量的car结构组成的动态数组。接下来,程序提示用户输入每辆车的生产商,和年份信息。最后程序将显示每个结构的内容,以下是我写的程序:
#include<iostream>
#include<string>
using namespace std;
int main()
{
struct car
{
string maker;
int year;
};
int size;
car *one=new car [size];
cout<<"how many cars do you wish to catalog?";
cin>>size;
cin.get();
for(int i=0;i<size;i++)
{
cout<<"Car #"<<i+1<<":"<<endl;
cout<<"Please enter the make:";
getline(cin,one[i].maker);
cout<<"Please enter the year made:";
cin>>one[i].year;
cout<<endl;
}
cout<<"Here is your collection"<<endl;
for(int i=0;i<size;i++)
{
cout<<one[i].year<<endl;
}
return 0;
}
我是在linux下用emacs编的 编译无错误,运行后 输入size为2 当我输入第一组 maker和year后, 运行显示核心已转储,我把
cout<<"Please enter the make:";
getline(cin,one[i].maker);
代码删除后,程序可以正常运行。求大神指导
------解决方案--------------------
------解决方案--------------------
struct car
{
string maker;
int year;
};
int size;
car *one=new car [size];
cout<<"how many cars do you wish to catalog?";
cin>>size;
还没初始化size就直接用来new了?改法看#2
------解决方案--------------------
自己分配的one 最后没有delete
------解决方案--------------------
这就是编译器指出来的。
另外,不delete会引起内存泄漏。这是需要避免的。
------解决方案--------------------
size没给值就用了 同学
小弟编了个程序,:设计一个名为car的结构,用它存储下述有关汽车的信息:生产商、生产年份。编写一个程序,向用户询问有多少量汽车,随后,程序用new来创建一个由相应数量的car结构组成的动态数组。接下来,程序提示用户输入每辆车的生产商,和年份信息。最后程序将显示每个结构的内容,以下是我写的程序:
#include<iostream>
#include<string>
using namespace std;
int main()
{
struct car
{
string maker;
int year;
};
int size;
car *one=new car [size];
cout<<"how many cars do you wish to catalog?";
cin>>size;
cin.get();
for(int i=0;i<size;i++)
{
cout<<"Car #"<<i+1<<":"<<endl;
cout<<"Please enter the make:";
getline(cin,one[i].maker);
cout<<"Please enter the year made:";
cin>>one[i].year;
cout<<endl;
}
cout<<"Here is your collection"<<endl;
for(int i=0;i<size;i++)
{
cout<<one[i].year<<endl;
}
return 0;
}
我是在linux下用emacs编的 编译无错误,运行后 输入size为2 当我输入第一组 maker和year后, 运行显示核心已转储,我把
cout<<"Please enter the make:";
getline(cin,one[i].maker);
代码删除后,程序可以正常运行。求大神指导
linux
emacs
c++
------解决方案--------------------
int size;
//car *one=new car [size];
cout<<"how many cars do you wish to catalog?";
cin>>size;
car *one=new car [size];
------解决方案--------------------
struct car
{
string maker;
int year;
};
int size;
car *one=new car [size];
cout<<"how many cars do you wish to catalog?";
cin>>size;
还没初始化size就直接用来new了?改法看#2
------解决方案--------------------
int size;
cin>>size;
car *one=new(std::nothrow) car [size];
if(NULL == one)
return -1;
自己分配的one 最后没有delete
------解决方案--------------------
这就是编译器指出来的。
另外,不delete会引起内存泄漏。这是需要避免的。
------解决方案--------------------
size没给值就用了 同学