Is C++ Array passed by reference or by pointer?

前端 未结 3 607
臣服心动
臣服心动 2021-01-05 17:09

In school, our lecturer taught us that the entire array was passed by reference when we pass it to a function,.

However, recently I read a book. It

3条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-01-05 18:05

    The terminology used by your lecturer is confusing. However, in a function declaration such as

    void funcA(int []);
    

    the int[] is just another way of saying int*. So funcA can take any argument that is or can be converted to an int*.

    Arrays can decay to pointers to the first element in the right context. This means, for example, that you can assign an array's name to a pointer like this:

    int array[42];  // array is of type int[42]
    int * arr = array; // array decays to int*
    

    So, when you pass array to funcA,

    funcA(array); // array decays to int*
    

    funcA has a pointer to the first element of the array.

    But it is also possible to pass arrays by reference. It just requires a different syntax. For example

    void funcB(int (&arr)[42]);
    

    So, in your example, you are passing a pointer to the first element of the array, due to the signature of your function funcA. If you called funcB(array), you would be passing a reference.

提交回复
热议问题