将动态大小的数组传递给另一个函数的最“正确”的方法是什么?
bool *used = new bool[length]();
我想出了一些编译方法,但我不太确定正确的方法是什么。
E.g。
这些会传递值吗?
static void test(bool arr[])
static void test(bool *arr)
这个会通过引用传递吗?
static void test(bool *&arr)
由于
答案 0 :(得分:10)
实际上,两个第一个想法通过地址传递数组,第三个通过引用传递数据 。您可以设计一个小测试来检查:
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;
}
此测试的输出是
1
2
3
如果参数按值传递,则无法在函数内修改它,因为修改将保留在函数范围内。在C ++中,数组不能通过值传递,因此如果要模仿此行为,则必须传递const int*
或const int[]
作为参数。这样,即使数组是通过引用传递的,由于const
属性,它也不会在函数内部进行修改。
要回答您的问题,首选方法是使用std::vector
,但如果您绝对想使用数组,则应选择int*
。
答案 1 :(得分:4)
这里有一个混乱,在所有情况下指针'引用'你的数组。因此,当谈论按值传递或通过引用传递时,您应该清楚是否在谈论指针或它引用的数组。
答案 2 :(得分:1)
static void test(bool arr[])
static void test(bool *arr, size_t size)
对于静态/动态数组,如果您不想更改此指针的位置。
实施例: http://liveworkspace.org/code/c5e379ebe2a051c15261db05de0fc0a9
static void test(bool *&arr)
如果您想更改位置,请选择动态。
示例:http://liveworkspace.org/code/bd03b214cdbe7c86c4c387da78770bcd
但是,既然你用C ++编写 - 使用向量而不是原始动态数组。
答案 3 :(得分:1)
使用此:
void myFuncThatAcceptsDynamicArrays(bool* array, int size) {
// Do something (using the size as the size of the array)
}
由函数的用户提供有效的大小(这可能非常危险)。
答案 4 :(得分:0)
我总是将vector用于动态大小的数组。在所有情况下,C ++中的数组都是通过引用传递的,因为它们只传递了指针地址。在数组的情况下,没有原始的方法来传递值。