1

Trying to work with a linked list I came across this strange behavior. Here the code

contract Test{


  struct Node{
    uint x;
    uint linked; //index to next
    bool    nil;

  }
  Node [] public nodes;


  function Test(){
      nodes.push(Node(59,1,false));
      nodes.push(Node(100,2,false));
      nodes.push(Node(0,0,true));
  }


  function remove(uint nodeIdx){
      Node node = nodes[nodeIdx];
      Node linked = nodes[node.linked];
  }



}

If I call remove(1) I should expect to see node equal to {100,2,false}, but in the debugger I got the following

enter image description here

Or in other words, node.x is valued with the length of the nodes array. I wonder why

Moreover,

  • calling remove(anotherIndex) gives same results.
  • declaring local var Node storage node=nodes[nodeIdx] gives same result
3

I tried your code.

If you would have gone further in the debugging of the transaction, you would have seen that the correct values are set for node and linked.

enter image description here

declaring local var Node storage node=nodes[nodeIdx] gives same result

Using storage means you want to modify the state of the contract. You don't, so you should use memory which is cheaper too.

  • the remove( ) is supposed to change the state, I didn't show the code because I was focusing on referencing the state variable in the local scope. Actually, with an array of 4 elements I get node.x equal to 4 – Davide C Apr 1 '18 at 16:56
  • 2
    Agreed, you're not stepping through to the assignment, just the initialisation. Keep on stepping through and you'll see the correct values get assigned, and as Eilsha says, use memory variables, except where you want to store values in the block. When you want to do that in this case, set directly into the array eg via nodes[i].linked = newIndex. – norganna Apr 1 '18 at 16:57
  • Fine! You guys are right. It seems that graphically I was there with the debugger, but I was misled by the step into mechanics. I wonder this question shall be removed. – Davide C Apr 1 '18 at 17:05
  • 1
    Don't remove it, mark Elisha's answer as correct. Otherwise they spent time answering your question for no reward! (Which happens often enough as it is.) Plus it might just answer someone else who has the same issue at some point. – norganna Apr 1 '18 at 17:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.