[英]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. 您可以使用
std::vector
。
您可以提供一个指向数组第一个元素的指针+一个保存数组大小的第二个参数。
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). (通过将数组作为
int*
或int[]
传递,就C ++而言是相同的)。 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. 仅在要在函数中调整数组大小(例如,向其中添加新元素)时,才应使用
std::vector
,但否则可以坚持使用此方法,因为它更快。
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. 但是您说过,在将数组提供给函数之前已经创建了数组,使用引用没有意义。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.