1

I want to create a linked list with pointers. So I created a struct with a pointer and a value, the pointer being the one pointing to the next node of the list.

When I tried to set a poniter to the next node, i wanted to change the value of the next node by pointing at it from the first node, but when I try to show the value by accesing directly from the node structure i get another result, how can I make those to be equal? So that if I change one, no matter from where, the node changes its value.

This is for a university project where we need to use linked lists. I am just starting on the pointers subject so I accept any help.


#include <iostream>

struct node
{
    double val;
    node *nxt;
};

int main()
{
    node n1, n2;

    n1.val = 10;
    n1.nxt = new node{n2};

    n1.nxt->val = 20;

    std::cout << "List:\n";
    std::cout << n1.val << "\n"
              << n2.val << "\n";
}

Actual result:

List:

10

1.39065e-309

Expected result:

List:

10

20

2 Answers2

0

Change this line:

n1.nxt = new node{n2};

to

n1.nxt = &n2;

The reason what you did, didn't work is because you are creating a copy of n2 with new node{n2} (because C++ defines an implicit copy constructor for your class) and therefore it is this copy that had its val changed to 20.

By using the address-of [1] operator (&), you are able to assign the pointer to the address of n2 and thus able to change its value with n1.nxt->val = 20.

smac89
  • 39,374
  • 15
  • 132
  • 179
0

That's because you are actually allocating a new node, not actually setting your nxt link to hold the actual n2 node.

If you wish to add this node to the linked list, you should use the address of (&) operator:

n1.nxt = &n2;

Keep in mind this isn't recommended to create linked lists this way, particularly if you are doing this in a helper function like addNode() because n2 will get destroyed once the function exits. Thus, it's usually better to use new or equivalent for this when you can. That would look something like this:

n1.nxt = new node(/* node constructor parameters */);

Or, if you want to make a copy about an existing node:

n1.nxt = new node{n2};
  • Thank you! You provided an extra value to the answer :) – Facundo Gandolfo Oct 29 '19 at 22:36
  • You're welcome. Note that any answers you found useful you can up-vote. The one you found most helpful, you can accept by clicking the check mark next to it. –  Oct 30 '19 at 04:25