0

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 *&'
}
2
  • Gcc gives you a good diagnostic: "error: invalid initialization of non-const reference of type ‘Node*&’ from an rvalue of type ‘Node"* And answers your doubt competently. Commented Apr 2, 2013 at 6:34
  • Lol. Its deja-vu all over again.=P. The gcc error is about as concrete as you can get. The function is expecting a reference to an lvalue. You're passing an rvalue. There is no "there" there, so to speak. Commented Apr 2, 2013 at 6:36

2 Answers 2

2

&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.

Sign up to request clarification or add additional context in comments.

2 Comments

@Cheersandhth.-Alf Thanks! I just started wondering what was wrong.
I'm guessing the down-voter was thinking something about the phrase "r-value" when he pulled the trigger.
1

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);     
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.