簡體   English   中英

訪問向量元素時出現分段錯誤

[英]Segmentation fault while accessing vector elements

我正在學習如何在 C++ 中創建引用變量,並且在使用int &res = f[k]使res成為引用向量f的給定分量的變量時遇到了一些麻煩。

在此代碼中F(k)應返回 integer 輸入k的斐波那契數,通過記住向量中的先前調用F(0)F(1) 、... F(k-2)F(k-1)計算得出f但我得到一個Segmentation Fault ,這讓我覺得我沒有將res稱為向量f的一個組成部分。

這是我的代碼:

#include <iostream>
#include <vector>
using namespace std;
const int UNDEF = -1;
vector<int> f;

int F(int k) {
  int &res = f[k];  // I get "res: 0x0000000000000004 and &res: ??" when debugging
  if (res != UNDEF) return res; // EXC_BAD_ACCESS (code=1, address=0x4)
  if (k <= 1) return 1;
  return res = F(k-1) + F(k-2);
}

int main() {
  int k;
  cin >> k;
  vector<int> f(k+1, UNDEF);
  cout << F(k) << endl;
} 

我真的可以在這里使用一些幫助:非常感謝:)

亞歷克斯

全局向量變量f沒有元素 當你寫:

int &res = f[k];

您正在嘗試訪問它的第k個不存在的元素,這就是您此時遇到分段錯誤的原因。

請注意,在您的程序中,您有兩個同名的向量變量f 其中一個是局部變量,另一個是全局變量。

當你寫

int &res = f[k];

選擇的向量f是全局變量,並且由於全局向量f的大小為 0(空向量),因此當您嘗試訪問其第k個元素時,它會為您提供分段錯誤(未定義的行為),如此處所示

全局向量變量f沒有元素 當你寫:

int &res = f[k];

您正在嘗試訪問它不存在的第k個元素,這就是您在那時遇到分段錯誤的原因。

請注意,在您的程序中,您有兩個同名的向量變量f 其中一個是局部變量,而另一個是全局變量。

當你寫

int &res = f[k];

矢量f即選用的是全局變量和自全球矢量f的大小為0(空載體),當您試圖訪問其k個元素它給你分段錯誤(未定義行為)可以看出這里 那是因為全局向量未初始化。

試試這個(我添加了一個包含,我將f向量作為函數參數傳遞,就效率而言,您可能應該使用&來引用這個向量 - 請在此處查看更多信息):

#include <iostream>
#include <vector>
#include <bits/stdc++.h>
using namespace std;
const int UNDEF = -1;

int F(int k, vector<int> f) {
  int &res = f[k];
  if (res != UNDEF) return res;
  if (k <= 1) return 1;
  return res = F(k-1, f) + F(k-2, f);
}

int main() {
  int k;
  cin >> k;
  vector<int> f(k+1, UNDEF);
  cout << F(k, f) << endl;
  return 0;
}

或者,如果你想打印斐波那契系列(但我認為你想要的是f向量),你可以這樣做:

#include<iostream>    
using namespace std;      
void printFibonacci(int n){    
    static int n1=0, n2=1, n3;    
    if(n>0){    
         n3 = n1 + n2;    
         n1 = n2;    
         n2 = n3;    
 cout<<n3<<" ";    
         printFibonacci(n-1);    
    }    
}    
int main(){    
    int n;    
    cout<<"Enter the number of elements: ";    
    cin>>n;    
    cout<<"Fibonacci Series: ";    
    cout<<"0 "<<"1 ";  
    printFibonacci(n-2);  //n-2 because 2 numbers are already printed    
     return 0;  
}

非常感謝:我得到了一個后來被刪除的答案,但這是最簡單的解決方案:

#include <iostream>
#include <vector>
using namespace std;
const int UNDEF = -1;

int F(int k, vector<int>& f) {
  int &res = f[k];  
  if (res != UNDEF) return res;
  if (k <= 1) return 1;
  return res = F(k-1, f) + F(k-2, f);
}

int main() {
  int k;
  cin >> k;
  vector<int> f(k+1, UNDEF);
  cout << F(k, f) << endl;
} 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM