Passing an array by reference

后端 未结 5 1104
隐瞒了意图╮
隐瞒了意图╮ 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:14

    The following creates a generic function, taking an array of any size and of any type by reference:

    template<typename T, std::size_t S>
    void my_func(T (&arr)[S]) {
       // do stuff
    }
    

    play with the code.

    0 讨论(0)
  • 2020-11-22 12:14

    Arrays are default passed by pointers. You can try modifying an array inside a function call for better understanding.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-11-22 12:28

    It's just the required syntax:

    void Func(int (&myArray)[100])
    

    ^ Pass array of 100 int by reference the parameters name is myArray;

    void Func(int* myArray)
    

    ^ Pass an array. Array decays to a pointer. Thus you lose size information.

    void Func(int (*myFunc)(double))
    

    ^ Pass a function pointer. The function returns an int and takes a double. The parameter name is myFunc.

    0 讨论(0)
  • 2020-11-22 12:34

    It is a syntax. In the function arguments int (&myArray)[100] parenthesis that enclose the &myArray are necessary. if you don't use them, you will be passing an array of references and that is because the subscript operator [] has higher precedence over the & operator.

    E.g. int &myArray[100] // array of references

    So, by using type construction () you tell the compiler that you want a reference to an array of 100 integers.

    E.g int (&myArray)[100] // reference of an array of 100 ints

    0 讨论(0)
提交回复
热议问题