Frenky
Frenky

Reputation: 35

C++ returning array and display it

i would like to ask, why this code doesnt work...

int* funkce(){
    int array[] = {1,2,3,4,5};
    return(array);
  }

int main(){

    int* pp = funkce();
    int* ppk = pp+5;

    for (int *i = pp; i!=ppk; i++){
        cout << (*i) << endl;
    }

    system("PAUSE");
    return(0);
}

This code display:

1
16989655
4651388
- // -
253936048

So the poniter is out of array... But how is possible, that this code with array in Main is ok?

int main(){

    int a[] = {1,2,3,4,5};
    int* pp = a;
    int* ppk = pp+5;

    for (int *i = pp; i!=ppk; i++){
        cout << (*i) << endl;
    }
    system("PAUSE");
    return(0);
}

this code displayed:

1
2
3
4
5

Could you explain to me, why the first one doesnt work? Thank you!

Upvotes: 1

Views: 94

Answers (2)

Barry
Barry

Reputation: 303057

You're returning a pointer to a temporary which goes out of scope when the function ends. If you want to have a function return an array, you need to do one of:

std::array<int, 5> func() {
    // stack-allocated
    std::array<int, 5> a = {1, 2, 3, 4, 5};
    return a;
}

std::vector<int> func() {
    // heap-allocated
    std::vector<int> a = {1, 2, 3, 4, 5};
    return a;
}

int* func() {
    // heap-allocated, you have to remember to delete it
    int* a = new int[5]{1, 2, 3, 4, 5};
    return a;
}

etc. There's more options, but this should give you a good start.

Upvotes: 6

Deduplicator
Deduplicator

Reputation: 45664

Never return a local a pointer/reference to a variable, that memory is freed/re-used on return.

Using that dangling reference is Undefined Behavior and has unpredictable consequences.

Return an object, a pointer to heap-allocated memory, or save into a caller-supplied buffer.

Upvotes: 0

Related Questions