使用用户输入创建矩阵并在其中搜索元素的程序。在联机编译器和VScode Insiders上编译时出现分段错误,使我在1.181秒内以代码=3221225725退出[Done]。
使用了联机编译器。
还使用了VScode+MingW。
#include<iostream>
using namespace std;
int main()
{
int p;
do
{
int i,j,k,m;
int a[j];
m=0;
cout<<"Enter The Number Of Elements You Want In Your Array.n";
cin>>j;
cout<<"Give Your Input For The Array.n";
for(i=0;i<j;i++)
{
cin>>a[i];
}
cout<<endl<<"Your Array Is:n";
for(i=0;i<j;i++)
{
cout<<a[i]<<endl;
}
cout<<"Enter The Number You Want To Check.n";
cin>>k;
for(i=0;i<j;i++)
{
if(a[i]==k)
{
m=1;
}
}
if(m==1)
{
cout<<"You Number "<<k<<" Is Listed.n";
}
else
{
cout<<"You Number "<<k<<" Is Not Listed.n";
}
cout<<"If You Want A Re-Run Press 1 Or Else Press Any Other Number.n";
cin>>p;
}
while(p==1);
return 0;
}
int a[j];
使用未初始化的j
执行。请注意,可变长度数组(VLA(不在标准C++中。您应该使用std::vector
。
#include<iostream>
#include<vector> // add this to use std::vector
using namespace std;
int main()
{
int p;
do
{
int i,j,k,m;
// delete this
//int a[j];
m=0;
cout<<"Enter The Number Of Elements You Want In Your Array.n";
cin>>j;
// allocate an array *after* reading j
std::vector<int> a(j);
cout<<"Give Your Input For The Array.n";
for(i=0;i<j;i++)
{
cin>>a[i];
}
cout<<endl<<"Your Array Is:n";
for(i=0;i<j;i++)
{
cout<<a[i]<<endl;
}
cout<<"Enter The Number You Want To Check.n";
cin>>k;
for(i=0;i<j;i++)
{
if(a[i]==k)
{
m=1;
}
}
if(m==1)
{
cout<<"You Number "<<k<<" Is Listed.n";
}
else
{
cout<<"You Number "<<k<<" Is Not Listed.n";
}
cout<<"If You Want A Re-Run Press 1 Or Else Press Any Other Number.n";
cin>>p;
}
while(p==1);
return 0;
}