[英]why does my c++ code show segmentation fault
最近我試圖在 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;
}
每當我運行此代碼時,它都會顯示分段錯誤:代碼 output 錯誤
我嘗試在cin語句之前和之后使用cout語句稍微調試代碼,發現cin>>rows語句之前的cout被執行,但它之后的不是。 但話雖如此, cin 語句: cin>>t in main 可以毫無問題地執行。
有人可以幫我理解為什么我會遇到這個奇怪的段錯誤。
您必須告訴向量要存儲多少元素:
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。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.