【问题标题】:why does my c++ code show segmentation fault为什么我的 C++ 代码显示分段错误
【发布时间】:2020-02-27 17:03:12
【问题描述】:

最近我试图在 codechef - https://www.codechef.com/problems/SUMTRIAN 上解决这个问题。问题的自定义输入详情如下。

custom input details image

我为这个问题设计了以下代码

#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&gt;&gt;t[i][j]; 越界访问它。

标签: c++ error-handling segmentation-fault c++14


【解决方案1】:

您必须告诉向量要存储多少元素:

void func()
{  
    int i=0,j=0,rows=0;

    cin>>rows;

    vector<vector<int>> t(rows);

    for(i=0;i<rows;i++)  
    {
        t[i].resize(rows);

        for(j=0;j<=i;j++) 
            cin >> t[i][j];
    }
...

如果您不需要行 x 行的方阵,请使用 i + 1 调用 resize。

【讨论】:

猜你喜欢
  • 2017-11-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-02-16
  • 1970-01-01
  • 2020-08-01
相关资源
最近更新 更多