0

I have been trying to implement the Fibonacci series in linear time. I keep getting weird results each time I run the program. I am a newbie in C++.

int fib1(int n) {

    int arr[n];
    arr[0] = 0;
    arr[1] = 1;

    for (int i = 2; i < n; i++) {
        arr[i] = arr[i - 1] + arr[i - 2];

    }

    return arr[n];
}

int main() {

    int x = fib1(3);
    cout << x << endl;

    return 0;
}

The expected result is: 2

The result I am getting is: 4199748

Where did I mess up?

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
blockByblock
  • 366
  • 2
  • 4
  • 14
  • 1
    for (int i = 2; **i < n**; i++) { –  Aug 24 '19 at 01:48
  • I didnt understand what you mean? – blockByblock Aug 24 '19 at 01:50
  • 2
    `int arr[n]` is not valid C++ (VLAs are a feature of C, and not standard C++). And, if `arr` is an array with `n` elements, `return arr[n]` returns the value of a non-existent element, and causes undefined behaviour. – Peter Aug 24 '19 at 03:18

1 Answers1

8

If arr is of length n it doesn't have an element with index n and therefore you are accessing the array out-of-bounds in return arr[n]. That causes undefined behavior and anything could happen. You probably wanted an array of length n+1 and iteration up to i <= n.

Furthermore the array size must be known at compile time in standard C++. Therefore the variable-length array arr[n] is only allowed because your compiler has special support for it. Use std::vector instead.

walnut
  • 21,629
  • 4
  • 23
  • 59