Achmad Syaifudin
Achmad Syaifudin

Reputation: 35

how to print pointer in C++ with loop

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, :)

Upvotes: 0

Views: 673

Answers (2)

gbehar
gbehar

Reputation: 1299

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

Upvotes: 0

Jean-Fran&#231;ois Fabre
Jean-Fran&#231;ois Fabre

Reputation: 140148

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)

Upvotes: 1

Related Questions