简体   繁体   English

为什么有时对变量的引用表现为大小为1的数组?

[英]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.

相关问题 为什么 constexpr function 对于参考的行为不同? - Why does a constexpr function behave differently for a reference? 为什么std :: add_lvalue_reference的行为不符合预期? - Why does std::add_lvalue_reference not behave as expected? 可变大小的数组作为类成员:为什么要编译? - Variable size array as class member: why does it compile? 为什么C ++的`变量模板&#39;没有按预期运行? - Why does C++'s `variable template` not behave as expected? 为什么这两个静态 constexpr int 变量的行为“不同”? - Why does this two static constexpr int variable behave "differently"? 为什么堆栈中没有可变大小的数组? - Why no variable size array in stack? 为什么捕获无状态 lambda 有时会导致大小增加? - Why does capturing stateless lambdas sometimes results in increased size? 该程序有时会崩溃,有时工作得很好。 声明了一个变量数组,它的大小在程序中改变了 2 次 - The program crashes sometimes and works perfectly fine sometimes. A variable array is declared and its size changes 2 times in the program 由 auto 声明的变量有时是通过引用? - variable declared by auto sometimes is by reference? 为什么“const auto [x,y]”在绑定到引用类型时不能按预期运行? - Why does “const auto [x, y]” not behave as expected when binding to reference types?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM