I am learning how to make a reference variable in C++ and I am having some trouble when using int &res = f[k]
to make res
a variable that refers to a given component of vector f
.
In this code F(k)
should return the fibonacci number of integer input k
computed by memorizing the previous calls F(0)
, F(1)
,... F(k-2)
and F(k-1)
in vector f
but I get a Segmentation Fault
which makes me think I fail to refer res
as a component of vector f
.
Here's my code:
#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;
}
I could really use some help over here! Thanks a lot:)
Àlex
The global vector variable f
has no elements. And when you write:
int &res = f[k];
You're trying to access it's k
th element which doesn't exist which is why you get segmentation fault at that point.
Note in your program you have two vector variable with the same name f
. One of them is a local variable while the other one is a global variable.
When you write
int &res = f[k];
The vector f
that is chosen is the global variable and since the global vector f
has size 0(empty vector), when you try to access its k
th element it gives you segmentation fault(undefined behavior) as can be seen here.