#include <iostream>
usingnamespace 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 );
}
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.
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.