Блог пользователя adelnobel

Автор adelnobel, 10 лет назад, По-английски

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
  • Проголосовать: не нравится

»
10 лет назад, # |
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 <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 .