0

I want to add an array into a multidimensional array but the approach I use does not work.

contract Jar
{
    uint[][] m = [[4, 6], [5, 7]];
    uint[] v = [9, 8];
    m.push(v);

    function v() public view returns (uint)
    {
        return m[0][1];
    }
}

So how do I go about it?

1
  • m.push(v); is a function call, it must be placed inside a function or contractor. The contract scope is reserved for declarations / definitions. Otherwise, your approach is fine, just move the call to m.push(v);.
    – hroussille
    Commented Mar 14, 2022 at 15:45

1 Answer 1

1

Try this:

// SPDX-License-Identifier: MIT
pragma solidity >=0.4.22 <0.9.0;

contract Jar
{
  uint[][] m = [[4, 6], [5, 7]];

  function fillMultidimensionalArray(uint _firstValue, uint _secondValue) public {
    // You must declare the array which will be inserted into the multidimensional array
    uint[] memory v = new uint[](2);
    // Then after initializing, you must populate the array
    v[0] = _firstValue;
    v[1] = _secondValue;
    // And here, you put the array 'v' into 'm' (multidimensional array)
    m.push(v);
  }

  function getV(uint _firstIndex, uint _secondIndex) public view returns (uint)
  {
    return m[_firstIndex][_secondIndex];
  }

}
2
  • Bless your soul, IT WORKED!!!! I really appreciate.
    – user96316
    Commented Mar 15, 2022 at 9:19
  • Please, select my answer as accepted to help other person who have the same problem. Thank you so much! Commented Mar 15, 2022 at 13:42

Your Answer

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