开发者

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 mai开发者_如何学编程n() should carry the result as well, but I'm obviously wrong. Any hint of what I'm missing? Thank you!


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?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜