c++pointerspointer-address

Pointer address does not change in a link list


My problem is q->next always prints the same address, but I assigned q = &x;. Why it is not printing different addresses?

#include <stdio.h>


class Node
{
public:
    int val;
    Node *next;
    Node(int v,Node *p) { val=v, next=p; }
};


int main()
{
    Node head(0, NULL);
    Node *q = &head;

    int i = 5;
    while (i>0)
    {
        Node x(i * 10, q);
        q = &x;
        printf("# %d %p\n", q->val, q->next);
        i--;
    }
}

Solution

  • This has to do with the way x is allocated: It is a local variable inside the main function. That means it is allocated on the stack, at a specific position. You are reusing the same piece of memory all the time. Instead, try allocating memory for new nodes (new).