-1

The following program is supposed to print fibonacci numbers upto given terms:

#include <iostream>
#include <string>

using namespace std;

int* fibo(int);

int main()
{
    int num,  *ptr;
    cout << "How many numbers in fibonacci series? ";
    cin >> num;

    ptr = fibo(num);

    for (int i = 0; i < num; i++)
    {
        cout << *(ptr + i) << " ";
    }

}

int* fibo(int n)
{
    int arr[50];
    arr[0] = 1;
    arr[1] = 1;
    for (int i = 2; i < n; i++)
    {
        arr[i] = arr[i - 1] + arr[i - 2];
    }

    return arr;
}

But it doesn't work. Only the first two elements of fibonacci series are being printed correctly.

Sparsh
  • 25
  • 1
  • 4

3 Answers3

2

You have to change arr to pointer.

int *arr =new int(50);

Because the way you create arr is creating a local variable . And local variables are destroyed after the function or class that they exist finish working. So you can't keep that address after fibo function to reach arr afterwards.

Enver Evci
  • 186
  • 6
1

Currently you are returning an pointer to an array that no longer exists once fibo exits. You need to make the array persistent by using dynamic memory allocation

 int* fibo(int n)
 {
   int* arr = new int[n]; // use n here because your loop does too!!
   arr[0] = 1;
   arr[1] = 1;
   for (int i = 2; i < n; i++)
   {
     arr[i] = arr[i - 1] + arr[i - 2];
   }

   return arr;
 }

Now arr points to an array of integers on the heap so you can safely access if after fibo() exits. Because it is persistent, you need to release the memory after you are finished so you must also call

delete[] ptr;

after your loop in main() before exiting. You should take a look at std::vector to do this kind of thing (unless this is a class exercise and you have been told not to)

mathematician1975
  • 21,161
  • 6
  • 59
  • 101
1

The algorithm you use is correct, but your C code is not. In your Fibo function, you create a automatically allocated array (Allocated on the stack), which means that this array will be deleted as soon as the function reaches its end. That explains why the values are not displayed correctly.

If you want to correct that, what about allocating your array in your main, and passing a pointer to that array to your Fibo function? Then, instead of returning a pointer to an array, you simply modify the array inside the Fibo function.

int main(int argc, char * argv[]){
    int arr[50];
    // (...)
    fibo(num, arr);
}

void fibo(int arr[50], int num){
    // (...)
}

The main advantages of this solution against others (That consist of dynamically allocating the array within the Fibo function) are:

  • You don't need to worry about memory allocation.
  • Stack allocation is always more efficient than heap allocation.
IAmJohn
  • 183
  • 1
  • 6