Passing an array by reference

后端 未结 5 1162
隐瞒了意图╮
隐瞒了意图╮ 2020-11-22 11:52

How does passing a statically allocated array by reference work?

void foo(int (&myArray)[100])
{
}

int main()
{
    int a[100];
    foo(a);
}

5条回答
  •  执笔经年
    2020-11-22 12:25

    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];.

    EDIT: Some clarification.

    void foo(int * x);
    void foo(int x[100]);
    void foo(int x[]);
    

    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]);
    

    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.

提交回复
热议问题