0

Remix accepts the following code and allows me to deploy the contract:

pragma solidity 0.4.24;

contract bytes32array {



mapping(address => uint)[] balances;            


    function addBalance(address _address, uint _index, uint _amount) public {       
        balances[_index][_address] = _amount;                                       

    }


    function getBalance(address _address, uint8 _index) public view returns(uint) {
          return balances[_index][_address];

    }


}

However, when I try to use the "addBalance" function, I just get an error (both in Javascript VM and through web3/testrpc). I get the error "VM Exception while processing transaction: invalid opcode". I can't figure out what I'm doing wrong, especially since the syntax is accepted.

1 Answer 1

1

Your access is out of bounds. balances has a length of 0, so balances[x] for any x will be an error. You can use balances.push(...) or balances.length += 1 to extend the array.

Or use a mapping of mappings instead, if you don't intend to use consecutive IDs:

mapping(uint256 => mapping(address => uint256));
2
  • How do I use "balances.push" in this case? I try pushing the address and amount, or just the address, but neither works. Commented Jun 14, 2018 at 1:13
  • Yeah, I don't think you can use balances.push at all here, since the thing you'd have to push would be a new mapping (and there's no defined copy from memory to storage of a mapping).
    – user19510
    Commented Jun 14, 2018 at 2:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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