0

I want to print pointer value after get the address from function return processing but, when i try to print 1 by 1 the program is fine ... but when i try to use loop, something happen ..

heres my code :

    int *fibo(int input){
        int a=0,b=0,fib=1;
        int arrfibo[input];
        int *arrfib;

        for(int i=0;i<input;i++){
            a = b;
            b = fib;
            arrfibo[i] = fib;
            fib = a + b;
        }

        arrfib = arrfibo;

        cout << arrfib << endl;

        return arrfib;
    }

    main(){
        int inp;
        cout << "Enter number of fibonancci = ";
        cin >> inp;
        int *arr;

        arr = fibo(inp);


        for(int i=0;i<inp;i++){
            cout << *(arr + i) << " ";
        } // something wrong here the result is (1 1 4462800 4663360 0)
    }

thanks, :)

3
  • 4
    you're returning a local variable address. Undefined behaviour when it goes out of scope. Commented Nov 24, 2016 at 16:03
  • Maybe you are accessing a memory location which is't properly assigned, i.e, contains garbage value. Commented Nov 24, 2016 at 16:04
  • VLA's aren't standard c++. You should turn off gcc extensions for more portable code. Commented Nov 24, 2016 at 16:12

2 Answers 2

1

you're returning a local variable address. Undefined behaviour when it goes out of scope.

Instead, use new to create an array

 int *fibo(int input){
        int a=0,b=0,fib=1;
        int arrfibo = new int[input];   // <-- minimal line to change
        int *arrfib;   // <-- this is useless, you can directly return arrfibo

(of course you have to delete [] the array when not used anymore. An alternative is to use vector<int> to avoid all that new/delete problems)

Sign up to request clarification or add additional context in comments.

Comments

0

This array was allocated on the stack in "fibo", when you are accessing it in main it was already released and you cannot access it

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.