0
#include<vector>
using namespace std;

struct x{
    vector<int> y;
};
void magic(struct x& d)
{
    d.y[0] = 5;
}
int main() {
    struct x d;
    d.y = {1,2,3};

    struct x* z = &d;
    magic(*z);

    cout<<z->y[0];
    return 0;
}

Is this code valid and how? Can we pass *z to a function which requires c++ reference.

1 Answers1

0

The pointer z points to the object d.

struct x* z = &d;

Dereferencing the pointer you get the lvalue of the object d that is passed as an argument to the function by reference

magic(*z);

So there is no magic.

In fact these two calls

magic( *z );

and

magic( d );

are equivalent. The only difference is that in the first call there is used a more complicated expression.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335