Reputation: 89
I am having difficulty understanding why below code does not compile under Visual Studio 2012, error already embedded in below code. I feel it has something to do with referencing stack object, but not quite sure. Can someone help?
Thanks
#include <iostream>
typedef struct Node {
Node *next;
} Node;
void test(Node *&p) {
p=p->next;
}
void main() {
Node *p1=new Node();
test(p1); // this line compiles okay
Node p={0};
test(&p); // error C2664: 'test' : cannot convert parameter 1 from 'Node *' to 'Node *&'
}
Upvotes: 0
Views: 91
Reputation: 8886
You're passing a variable by address, not a pointer to a variable by reference. I think this will work:
void main() {
Node *p1=new Node();
test(p1);
Node p={0};
Node* p2 = &p;
test(p2);
}
Upvotes: 1
Reputation: 62048
&p
is not a variable of type Node*
. It's a constant of type Node*
.
Even if you could somehow take a reference to p
and pass it to test()
, p=p->next;
would still fail because you can't assign to a constant.
Upvotes: 2