1

I have created an extremely simple linked list example in C++ to practice some interview questions. I am having one strange issue that I can't really seem to understand:

while( cur )
{
    cout << "Index: " << indx << endl <<
        "Current Add:\t" << &cur << endl <<
        "Value:\t\t" << cur->val << endl <<
        "Next Add:\t" << &cur->next << endl << 
        "Ran Add:\t" << &cur->ran << endl <<
        "Ran Val:\t" << cur->ran->val << endl << endl;
    cur = cur->next;
    ++indx;
}

I am using this code to iterate through and print the list. It works fine. HOWEVER. The address of the current node is always the same. The list contains a int value and a pointer to a next node as well as a pointer to a random address in the list. The addresses and Values are assigned correctly and I can see the "next" address fine. But when it assigns that to the current node it always seems to point to the same address..

The only thing I can assume is that during execution it moves "cur" to some register and so always shows this address rather than the location in memory. Does this make sense? Would this be correct or is there something I am missing? This does not affect my implementation in any way it is just some strange behaviour that I would like to better understand.

Thanks

1
  • 5
    The address of the current node is the value of cur. You are instead printing &cur - the address at which the variable cur itself is located. Naturally, cur doesn't magically jump around in memory - its value changes, but its address doesn't. Commented May 18, 2015 at 2:52

1 Answer 1

6

You're printing:

"Current Add:\t" << &cur << endl <<

This is the address of the variable:

struct node *cur;

The address of that pointer (not the address it points to!) will of course not change. You probably intended to write:

"Current Add:\t" << cur << endl <<
Sign up to request clarification or add additional context in comments.

1 Comment

Oh god, of course, stupid mistake. Thanks for the quick answer.

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.