简体   繁体   中英

How do I pass a reference to an array, whose size is only known at run-time, as a function parameter?

I have an array that is being dynamically created based on user input, and I need to pass that array to a function where it will be manipulated and the results passed back out to the original array. When I try to use

void MyFunction(int (&MyArray)[])

my compiler complains that it doesn't know how big the array is.

You can't. You could use a std::vector though.

您可以提供一个指向数组第一个元素的指针+一个保存数组大小的第二个参数。

If it's just an array, why not pass the array itself and its size as a second parameter? (by passing the array as an int* or int[] , same thing as far as C++ is concerned). As the value of the variable containing your array is only the pointer to the first element of your array, you don't end up killing your runtime by copying the contents of the array, but just a pointer which is as small as you can get in this case.

void MyFunction( int MyArray[], int size ) { /* edit the array */ }
int main() {
    // read nrElements
    // ...

    // create the array
    int *a = new int[nrElements];
    // populate it with data
    // ...
    // and then
    MyFunction(a, nrElements);
}

You should use a std::vector only if you want to resize the array in your function (eg add new elements to it), but otherwise you can just stick to this approach because it's faster.

Btw, the only case you would need a reference to an array is if you want to change the value of the variable you pass in when you call the function, as in, make it point to a different array. Like in:

void createMyArray(int* &array, int nrElements) {
    array = new int[nrElements];
    for (int i = 0; i < nrElements; ++i) {
        array[i] = 0;
    }
}

int *a = (int []) {1, 2, 3};
std::cout << a[0] << std::endl; // prints 1
createMyArray(a, 10);
// now  a  points to the first element of a 10-element array
std::cout << a[0] << std::endl; // prints 0

But you said the array is already created before providing it to the function, there's no point in using references.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM