简体   繁体   中英

C++ - Pass by Reference, Weird Thing for Array

As far as I know, C++ use Ampersand(&) to make a Pass by Reference Function. But I just tested this code, and I wonder why the second function seems similar with the first function. It seems the second function is a Pass by Reference Function now.

#include <iostream>
using namespace std;

void f1(int (&b)[5])
{
    b[0]=1;
}

void f2(int b[5])
{
    b[1]=2;
}

int main()
{
    int a[5];
    f1(a);
    f2(a);

    cout<<a[0]<<endl;
    cout<<a[1]<<endl;
}

Output:

1
2

Anybody can explain me about this? Thanks.

When you pass an array to a function, it degenerates to a pointer. So in either case, the results are the same.

So in case of f2 , b is a pointer, which points to the same location the array a starts from. Also remember array indexing [ a[i] ] and pointer arithmetic and de-referencing [ *(a+i) ] are synonymous expression. So in your second case, you end up updating the original array that was passed.

Now there is a subtle difference between both the declarations. In case of f1 , the parameter b is a reference to the original array a , so b is still the same array with all the characteristic of the source array. In case of the second expression, b is just a pointer that incidentally points to the location of the array a .

Considering the fact that the parameters are ideally different, they have different behavior

  1. Sizeof for the reference variable returns the actual size of the array.
  2. You cannot modify the reference parameter inside the function.

For the sake of completeness, here is an updated program which will give you more idea on how the behavior differs.

#include <iostream>
using namespace std;

void f1(int (&b)[5])
{
    std::cout<<sizeof(b)<<std::endl;
    //b = new int[5]; -- Will give compile error
    b[0]=1;
}

void f2(int b[5])
{
    std::cout<<sizeof(b)<<std::endl;
    //b = new int[5]; -- Will compile fine
    b[1]=2;
}
int main()
{
    int a[5];
    f1(a);
    f2(a);

    cout<<a[0]<<endl;
    cout<<a[1]<<endl;
}

Arrays are always "passed by reference" . The array's name is a pointer
to the array's first element. So the parameter int b[5] in the
second function is basically the same as int* b .

Arrays are passed by the pointer by default, ie, the base address of the array. So here in f2() the base address of a is copied to b so that, it can be accessed from the function in normal pointer manner.

When you are passing the array by it's reference, it doesn't occupy any extra memory it just renaming it, you still have access to that array in the same manner(by using the alias name given to it) you do have at the block you are originally defining it..

Hope it helped...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM