1

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!

1

2 Answers 2

6

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.

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

8 Comments

std::vector is the one to use (IMHO)
@pm100 Why not std::array?
because the std:array will return a copy of the array (more expensive in general although probably trivial here). std::vector returns a pointer to the array on the heap. And the perf of vector and array are the same
@pm100 If you have std::array<int, 5> a = func(), the array won't be copied, it will be constructed in place. The determination to use one or the other is entirely use-case based.
according to your own comment it was allocated on the stack of the func. Cant be on the func stack when I return it
|
0

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.

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.