[英]Why does a reference to a variable behave as an array of size 1 sometimes?
#include <iostream>
using namespace std;
void outputFirst(int x[]) {
cout << x[0] << endl;
}
int main() {
int x = 40;
// works
outputFirst(&x);
// works
int *y = &x;
cout << y[0] << endl;
// invalid types ‘int[int]’ for array subscript
cout << &x[0] << endl;
return 0;
}
Why can I use a reference to an int as an array when I pass it to a function or assign it to another variable first, but not directly? 当我将int传递给函数或先但不直接将其分配给另一个变量时,为什么可以使用对int作为数组的引用?
I'm using g++-6.3. 我正在使用g ++-6.3。
Why can I use a reference to an int 为什么要使用对int的引用
Note that &x
doesn't mean reference to x
, it means taking the address of x
and you'll get a pointer (ie int*
) from it. 请注意, &x
并不意味着引用x
,这意味着获取 x
的地址,您将从其中获得一个指针(即int*
)。 So int *y = &x;
所以int *y = &x;
means taking the address from x
, then y[0]
means get the 1st element of the array pointed by the pointer (as if it points to the 1st element of the array which contains only one element (ie x
) ), so at last it returns x
itself. 表示从x
获取地址,然后y[0]
表示获取指针指向的数组的第一个元素(好像它指向仅包含一个元素(即x
)的数组的第一个元素),所以最后它返回x
本身。
And about why &x[0]
doesn't work, note that operator[]
has higher precedence than operator&
. 关于&x[0]
不起作用的原因,请注意, operator[]
优先级高于operator&
。 Then &x[0]
is interpreted as &(x[0])
, while x[0]
is invalid since x
is just an int
. 然后&x[0]
解释为&(x[0])
,而x[0]
无效,因为x
只是一个int
。
You should add parentheses to specify the precedence explicitly, eg 您应该添加括号以明确指定优先级,例如
cout << (&x)[0] << endl;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.