leeyang
leeyang

Reputation: 3

why does vector return miss some value?

int main(int argc, char argv)
{
    int myarray[] = {1, 2, 3, 5};
    std::vector<int> array(myarray, myarray + 4);
    std::vector<int> *p = testvector(array);
    std::vector<int>::const_iterator it;
    for(it=p->begin(); it != p->end(); ++ it)
    {
        printf("%d ", *it);
    }
    return 0;
}

std::vector<int> *testvector(std::vector<int> array) 
{
    return &array;
}

Above is my test code; what is wrong that it returned 0 0 3 5 instead of 1 2 3 5

Upvotes: 1

Views: 79

Answers (3)

nils
nils

Reputation: 2524

Change

std::vector<int> *testvector(std::vector<int> array) 

to

std::vector<int> *testvector(std::vector<int>& array) // Note the &

Otherwise the array is copied to a local variable, which is destroyed at the end of testvector() which invalidates the returned pointer.

Upvotes: 0

Humam Helfawi
Humam Helfawi

Reputation: 20264

this:

std::vector<int> *testvector(std::vector<int> array) 

should be replaced with:

std::vector<int> *testvector(std::vector<int>& array) 

Live Demo

However, this is not a real solution since there is no point from your example. I think you have an X problem and you are just posting the Y one. if you post your real problem, it will be easier to help you.

Upvotes: 0

Bathsheba
Bathsheba

Reputation: 234645

Look at std::vector<int> *testvector(std::vector<int> array) carefully. This is taking a deep copy of the input parameter array.

The returned pointer will be dangling once array is out of scope. The behaviour on dereferencing that pointer will be undefined. That's why your program is behaving oddly.

Interestingly, if you had written std::vector<int>& array as the parameter (i.e. passed by reference) then this would have worked, since you would be returning a pointer to the vector defined in main! This code would be extremely brittle though.

Upvotes: 3

Related Questions