【发布时间】:2020-02-27 17:03:12
【问题描述】:
最近我试图在 codechef - https://www.codechef.com/problems/SUMTRIAN 上解决这个问题。问题的自定义输入详情如下。
我为这个问题设计了以下代码:
#include <bits/stdc++.h>
using namespace std;
void func()
{
vector<vector<int>> t;
int i=0,j=0,rows=0;
cin>>rows; // to input no. of rows
// i think for this cin it shows a seg fault
// and also maybe for other cin lines
for(i=0;i<rows;i++)//input the elements from custom input and store in 2D
for(j=0;j<=i;j++) //matrix
cin>>t[i][j];
for(i=rows-2;i>=0;i--)
for(j=0;j<=i;j++)
t[i][j]=t[i][j]+max(t[i+1][j],t[i+1][j+1]);
cout<<endl<<t[0][0]; //element at this position will have max sum
}
int main() {
int t=0;
cin>>t;
while(t--)//for t test cases
func();
return 0;
}
每当我运行此代码时,它都会显示分段错误: code output error
我尝试在 cin 语句之前和之后使用 cout 语句稍微调试代码,发现 cout 在 之前>cin>>rows 语句被执行,但不是它之后的语句。但话虽如此, cin 语句 : cin>>t in main 得到执行没有任何问题。
谁能帮我理解为什么我会遇到这个奇怪的段错误。
【问题讨论】:
-
你的向量是空的。
cin>>t[i][j];越界访问它。
标签: c++ error-handling segmentation-fault c++14