adelnobel's blog

By adelnobel, 10 years ago, In English

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!

  • Vote: I like it
  • 0
  • Vote: I do not like it

»
10 years ago, # |
Rev. 2   Vote: I like it +7 Vote: I do not like it

You can't assign a vector element to a result of a function that changes the vector here is an example

#include <iostream>
    #include <vector>
    using namespace std;
    vector <int>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 <iostream>
    #include <vector>
    using namespace std;
    vector <int>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 .

  • »
    »
    10 years ago, # ^ |
      Vote: I like it 0 Vote: I do not like it

    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?