Hi,

Today I was writing some recursive code and it behaved in a very weird way and I couldn't find out why this happened,

Here is the code

http://ideone.com/cDrZs8

It gives runtime error, and doesn't assign the values correctly!

However if I do it like this

http://ideone.com/z5pOul

Everything just works perfectly! I feel I'm missing something but I couldn't figure it out for over half an hour and yet the code is simple (I suppose).

It would be greatly appreciated if anyone could point out the problem.

Thanks!

• 0

 » 7 years ago, # | ← Rev. 2 →   +7 You can't assign a vector element to a result of a function that changes the vector here is an example #include #include using namespace std; vector x; int go(){ x.push_back(5); return 4; } int main() { x.push_back(5); cout << x[0] << endl; x[0]=go(); cout << x[0] << endl; return 0; } the problem is #include #include using namespace std; vector x; int main() { x.push_back(5); cout << &x[0] << endl; x.push_back(5); cout << &x[0] << endl; return 0; } Got it ? it's not the same x[0] before and after the push , so you get in access violation runtime error .
•  » » 7 years ago, # ^ |   0 I think I quiet understand, what is the reason of this? Maybe because it saves the address of that variable and then goes to evaluate the function so when it returns, this address no longer belongs to the vector?
•  » » » 7 years ago, # ^ | ← Rev. 2 →   +3 exactly , that's the problem , [discover it barely :D] try it here
•  » » » » 7 years ago, # ^ |   0 Great tool! First time to see it. Thanks a ton for answering you saved my day :D :D
•  » » » » » 7 years ago, # ^ | ← Rev. 2 →   +3 You're welcome ;)