C++ 数组是如何传递的?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2559896/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How are arrays passed?
提问by There is nothing we can do
Are arrays passed by default by ref or value? Thanks.
默认情况下,数组是通过 ref 还是 value 传递的?谢谢。
回答by
They are passed as pointers. This means that all information about the array size is lost. You would be much better advised to use std::vectors, which can be passed by value or by reference, as you choose, and which therefore retain all their information.
它们作为指针传递。这意味着有关数组大小的所有信息都将丢失。建议您使用 std::vectors 更好,它可以根据您的选择按值或按引用传递,因此保留了它们的所有信息。
Here's an example of passing an array to a function. Note we have to specify the number of elements specifically, as sizeof(p) would give the size of the pointer.
这是将数组传递给函数的示例。请注意,我们必须具体指定元素的数量,因为 sizeof(p) 将给出指针的大小。
int add( int * p, int n ) {
int total = 0;
for ( int i = 0; i < n; i++ ) {
total += p[i];
}
return total;
}
int main() {
int a[] = { 1, 7, 42 };
int n = add( a, 3 );
}
回答by fredoverflow
First, you cannot pass an array by value in the sense that a copy of the array is made. If you need that functionality, use std::vector
or boost::array
.
首先,在创建数组副本的意义上,您不能按值传递数组。如果您需要该功能,请使用std::vector
或boost::array
。
Normally, a pointer to the first element is passed by value. The size of the array is lost in this process and must be passed separately. The following signatures are all equivalent:
通常,指向第一个元素的指针是按值传递的。数组的大小在此过程中丢失,必须单独传递。以下签名都是等价的:
void by_pointer(int *p, int size);
void by_pointer(int p[], int size);
void by_pointer(int p[7], int size); // the 7 is ignored in this context!
If you want to pass by reference, the size is part of the type:
如果要通过引用传递,大小是类型的一部分:
void by_reference(int (&a)[7]); // only arrays of size 7 can be passed here!
Often you combine pass by reference with templates, so you can use the function with different statically known sizes:
通常您将按引用传递与模板结合使用,因此您可以使用具有不同静态已知大小的函数:
template<size_t size>
void by_reference(int (&a)[size]);
Hope this helps.
希望这可以帮助。
回答by Thomas Bonini
Arrays are special: they are always passed as a pointer to the first element of the array.
数组很特别:它们总是作为指向数组第一个元素的指针传递。