derrdji
derrdji

Reputation: 13321

in C++ how can I pass a static array to an object as a parameter, and modify the original array in there?

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!

Upvotes: 0

Views: 499

Answers (1)

Oliver Charlesworth
Oliver Charlesworth

Reputation: 272687

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?

Upvotes: 3

Related Questions