Proper way to pass dynamic arrays to other functions

后端 未结 5 1169
再見小時候
再見小時候 2020-12-16 21:31

What\'s the most \"proper\" way to pass a dynamically sized array to another function?

bool *used = new bool[length]();

I\'ve come up with

5条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-16 22:23

    Actually, the two first ideas pass the array by address and the third passes the array by reference. You can devise a little test to check this:

    void test1(int* a) {
        a[0] = 1;
    }
    
    void test2(int a[]) {
        a[1] = 2;
    }
    
    void test3(int *&a) {
        a[2] = 3;
    }
    
    int main() {
        int *a = new int[3]();
        a[0] = 0;
        a[1] = 0;
        a[2] = 0;
    
        test1(a);
        test2(a);
        test3(a);
    
        cout << a[0] << endl;
        cout << a[1] << endl;
        cout << a[2] << endl;
    }
    

    The output of this test is

    1
    2
    3
    

    If a parameter is passed by value, it cannot be modified inside a function because the modifications will stay in the scope of the function. In C++, an array cannot be passed by value, so if you want to mimic this behaviour, you have to pass a const int* or a const int[] as parameters. That way, even if the array is passed by reference, it won't be modified inside the function because of the const property.

    To answer your question, the preferred way would be to use a std::vector, but if you absolutely want to use arrays, you should go for int*.

提交回复
热议问题