views:

59

answers:

1

The array has to be on the stack, and I need to modify the elements. Here is what I have:

    Class Me {
private:
    int *_array;
    void run(){
        for (int i = 0 ; i < 10; ++i) {
            _array[i] += 100;
        }
    }
public:
    Me(int array[]) {
        _array = array;
    }
};

This is main:

    int array[10] = {0, 1,2,3,4,5,6,7,8,9};
    Me m(array);
    m.run();
    for (int i = 0 ; i < 10; ++i) {
        cout << array[i] << " ";
    }
    cout << endl;

I thought array passing are done by reference, so whatever I did in run(), the array in main() should carry the result as well, but I'm obviously wrong. Any hint of what I'm missing? Thank you!

+3  A: 

When I fix your code so that it actually compiles, I get the output

100 101 102 103 104 105 106 107 108 109

Is this not what you expected?

Oli Charlesworth
yes, it is. There were some bugs in my code, and I thought I forgot about how I could use array parameters. your answer just helped me realizing I did something else wrong. thank you!
derrdji