通过引用传递数组 [英] Passing an array by reference
问题描述
如何通过引用传递静态分配的数组?
How does passing a statically allocated array by reference work?
void foo(int (&myArray)[100])
{
}
int main()
{
int a[100];
foo(a);
}
(&myArray)[100]
是否有任何意义,或者它只是一种通过引用传递任何数组的语法?我不明白这里的单独括号后跟大括号.谢谢.
Does (&myArray)[100]
have any meaning or its just a syntax to pass any array by reference?
I don't understand separate parenthesis followed by big brackets here. Thanks.
推荐答案
这是数组引用的语法 - 您需要使用 (&array)
向编译器说明您需要引用到一个数组,而不是(无效的)引用数组 int &数组[100];
.
It's a syntax for array references - you need to use (&array)
to clarify to the compiler that you want a reference to an array, rather than the (invalid) array of references int & array[100];
.
一些说明.
void foo(int * x);
void foo(int x[100]);
void foo(int x[]);
这三种是声明同一个函数的不同方式.它们都被视为接受一个 int *
参数,您可以将任何大小的数组传递给它们.
These three are different ways of declaring the same function. They're all treated as taking an int *
parameter, you can pass any size array to them.
void foo(int (&x)[100]);
这仅接受 100 个整数的数组.您可以安全地在 x
This only accepts arrays of 100 integers. You can safely use sizeof
on x
void foo(int & x[100]); // error
这被解析为引用数组"——这是不合法的.
This is parsed as an "array of references" - which isn't legal.
这篇关于通过引用传递数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!