Proper way to pass dynamic arrays to other functions

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*.

Leave a Comment