user4418808
user4418808

Reputation:

Passing by Pointers vs Passing by reference

I have understood the fact that a calling a function by reference can be done in two ways either passing the variable by reference or passing the variable by pointers. But now I am stuck at the o/p difference of it

#include <iostream>

using namespace std;
void test(int *a)
{

    cout<<&a<<"  ";
}
int main()
{
   int a[4]={5,3,8,2};
   for(int i=0;i<4;++i)
   {
        test(&a[i]);    
   }
    return 0;
}

This gives me the same address location but shouldn't it be different as we are passing &a[i]--> the address of ith element every time it is called which is received by the pointer a but I get the same address every time which is the starting address of the array while if I modify the function call somewhat I get the expected o/p which is from the below code

#include <iostream>

using namespace std;
void test(int &a)
{

    cout<<&a<<"  ";
}
int main()
{
   int a[4]={5,3,8,2};
   for(int i=0;i<4;++i)
   {
        test(a[i]);    
   }
    return 0;
}

Upvotes: 0

Views: 139

Answers (1)

juanchopanza
juanchopanza

Reputation: 227578

In the first example, you are printing the address of the pointer itself. That is a local variable of your function. If you print out the address of the thing it points too, you will see different addresses:

cout<< &(*a) << "  ";
cout << a << "  ";    // same as above

In your second example, the reference refers to the argument passed to the function. Getting the address of a reference is the same as getting the address of the object it refers to, because a reference is just an alias for an object.

Upvotes: 4

Related Questions