0

I'm running into a problem with solidity with structures containing arrays, can you help me see what I'm missing?Any help would be greatly appreciated!

 struct Info {
    uint a;
    uint256 b;
    uint[] data;
}

mapping(address => Info) infos;

function set() public {
    infos[msg.sender].a = 1;
    infos[msg.sender].b = 2;
    infos[msg.sender].data.push(3);
}

function get() public {
      infos[msg.sender].a; //yes It is equal to 1
      infos[msg.sender].b; //yes It is equal to 2
      infos[msg.sender].data[0]; //The problem here is that anyone calling this function can read data[0]=3
}
1
  • My problem is that when someone calls set() and anyone else calls get(), data[0] returns 3, which is weird
    – zmy
    Nov 2, 2021 at 10:52

1 Answer 1

0

So this works as you said. you pushed value 3 to the array and it returns value 3 at 0 index of the array. if you want data array has 3 elements you should push 3 times a value maybe 0.

1
  • Maybe my demo gave you the wrong idea, but I already know where I went wrong. View-decorated functions should not use msg.sender, it is empty address!
    – zmy
    Nov 3, 2021 at 8:39

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.