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.

CreatedAMadman
  • 190
  • 1
  • 14

1 Answers1

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));
user19510
  • 27,999
  • 2
  • 30
  • 48
  • How do I use "balances.push" in this case? I try pushing the address and amount, or just the address, but neither works. – CreatedAMadman Jun 14 '18 at 01: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 Jun 14 '18 at 02:07