【问题标题】:timeout: the monitored command dumped coretimeout:被监控的命令转储核心
【发布时间】:2022-01-16 03:18:39
【问题描述】:

我正在在线编译器中运行此代码,显示转储核心错误该程序找到两对的最高乘积。

#include <bits/stdc++.h>
using namespace std;
void maximumproductpair(int arr[],int n){
sort(arr,arr+n);
reverse(arr,arr+n);
int prod;
for(int i=0; i<n; i++){
cout<<arr[i];
}
prod=prod*arr[0];
prod=*arr[1];
cout<<prod;
}

int main() 
{
int t,n;
int arr[n];
cin>>t;
cout<<"\n";
cin>>n;
cout<<"\n";
  while(t--){
  for(int i=0; i<n;i++){
  
     cin>>arr[i];
   }
 }
maximumproductpair(arr,n);
  return 0;
}

在代码中一切正常,那么为什么会出现这个错误?

【问题讨论】:

  • 你没有初始化 int 你的 while(t--) 没有循环停止

标签: c++ arrays


【解决方案1】:

错误 1

问题是您的tn 变量未初始化。这意味着tn 都具有垃圾值。当你写的时候:

int t,n;
int arr[n];//UNDEFINED BEHAVIOR because n has garbage value

您有未定义的行为,因为n 具有垃圾值

这就是为什么建议这样做

始终在本地/块范围内初始化内置类型。

错误 2

第二,注意在 C++ 中数组的大小必须是一个编译时常数。所以以下面的代码sn-ps为例:

int n = 10;
int array[n]; //INCORRECT

上面的正确写法是:

const int n = 10;
int array[n]; //CORRECT 

同样,

int n;
cin >> n;
int array[n]; //INCORRECT becasue n is not a constant expression

另请注意,某些编译器提供编译器扩展,让您拥有可变长度数组。你可以在Why aren't variable-length arrays part of the C++ standard?阅读更多关于它的信息。

如果您想将数组的大小作为用户的输入,那么您应该使用 动态大小的容器,例如 std::vector

int n;
cin >>n;
std::vector<int> array(n);// CORRECT, this creates a vector of size n of elements of type int

另见Why should I not #include <bits/stdc++.h>?

【讨论】:

  • 谢谢,但即使不使用 const 本身,从用户那里获取输入也不会显示任何错误。
  • @igneousspark 是的,您看不到任何错误,因为某些编译器(例如您正在使用的编译器)提供编译器扩展,可以让您编写int n; cin &gt;&gt; n; int arr[n];。这就是您看不到错误的原因,因为您使用的编译器提供了一个扩展,可以让您这样做。只是它不是标准的 C++。阅读更多关于它的信息here
猜你喜欢
  • 1970-01-01
  • 2017-11-17
  • 2021-11-15
  • 2015-05-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多