fibonacci

Why is my code ONLY printing the first two integers of the sequence??

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
  #include <iostream>
    using namespace std;

    int fibonacci( int n )
    { 
        int tmp;
        int a = 1;
        int b = 1;        

        for (int i = 0; i < n-2; i ++) 
        {
             tmp = a+b;
            a = b;
             b = tmp;
        }
        return b;
   }

   int* computeFibonacciSequence(int& n)
   {
        int arr[8];
        n = 8;
        for (int k = 0; k < n; k++)
        {
            arr[k] = fibonacci( k );
        }
        return arr;
    }

    int main()
    {
        int m;
        int* ptr = computeFibonacciSequence(m);
        for (int i = 0; i < m; i++)
        {
            cout << ptr[i] << ' ';
        }
        return( 0 );
    } 
see if it works if you put the word 'static' in front of
int arr[8];
Last edited on
I've tried that a few times but get some strange values like : 1 0 0 0 4196528 0 4196214 0
Oh yeah it's working!! why is that? can you please explain why it wasn't working?
arr was being destroyed when the function ended. It no longer existed, and your pointer to it was where it used to be, but is no longer!
static makes it stick around forever. Its not a good fix for real code, but for something this small, its fine to do this. (It burns memory if you do it all over the place in big programs, not at all an issue here).


a cleaner fix is to pass arr into the function from main, or allocate it as a pointer in the function and destroy it in main when done. A dirty fix would be to make arr global.


for fun, you can try computing the next value by multiplying by 1.618 when N gets bigger. It does not work for the first few values in the series, though. Youll want to look up a lot more digits of the number if you try that. It works and its fast, but it takes a little wiggling to get it right.



Last edited on
thank you so much, is this concept related to dynamically allocating an array ? like
int *arr = new[ n ] and then initializing inside the main?
the concept is that variables that exist in a function are destroyed when the function ends.

now a pointer lesson...

int *foo()
{
int * p; //this is a local variable in the function.
p = new int[10]; //asks the operating system to hold onto a block of memory holding 10 integers
return p;
} //p is GONE. But the memory we reserved is still ours.

int * p2 = foo(); //p2 is valid. the memory we allocated is passed back into p2.

delete[] p2; //releases the memory back to the OS.

So, while the local variable p is lost, the memory is not. This is one of several ways around your problem. Its fairly clean but some coding standards prefer to avoid having to KNOW to delete memory that was allocated someplace else. Object oriented programming cleans that issue up, though. You will get to that.





Topic archived. No new replies allowed.