1
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

2
  • 5
    You are returning a reference to a temporary value. That's undefined behavior. Commented Jan 12, 2016 at 8:43
  • The array in testvector is a copy of the array you passed in. Commented Jan 12, 2016 at 9:28

3 Answers 3

3

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.

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

Comments

0

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.

Comments

0

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.