0

This doesn't work in the contract body (a storage declaration):

uint8[][3] foo = [ [1,2,3], [], [0] ];

The error being:

TypeError: Unable to deduce common type for array elements

But neither does this work:

uint8[][3] foo = [ uint8[]([1,2,3]), uint8[]([]), uint8[]([0]) ];

With the error:

TypeError: Explicit type conversion not allowed from "uint8[3] memory" to "uint8[] memory".

And also, this doesn't work:

uint8[][3] foo = [ uint8[]([uint8(1),uint8(2),uint8(3)]), uint8[]([]), uint8[]([uint8(0)]) ];

with the same error as above.

But why? In the second example, the array literals are not uint8[3], they are uint8[] - which should match what the array declaration has (the intention being to create an array of 3 elements of uint8[]).

Is it even possible to initialise a multidimensional array of that shape in Solidity?

1 Answer 1

2

In Solidity, you can't directly initialize a storage array with variable-length inner arrays on storage declaration.

However, you can create a memory array in a function and store it in a storage array.

Here is an example:

contract ArrayExample {
    uint8[3][] public foo;

    constructor() {
        // Initialize the array
        foo.push([1, 2, 3]);
        foo.push([0, 0, 0]);
        foo.push([4, 5, 6]);

    }

    function getFoo() public view returns(uint8[3][] memory) {
      return foo;
    }

    function getFooByIndex(uint i) public view returns(uint8[3] memory) {
      return foo[i];
    }
}

edit: I'm not entirely sure what your specific goal is, but I've provided a possible solution below that may help you:

contract ArrayExample {
    uint8[][3] public foo;

    constructor() {
        // Initialize the array
        foo[0] = [uint8(1), 2, 3];
        foo[1] = new uint8[](0);
        foo[2] = [uint8(0)];
    }

    function getFoo() public view returns(uint8[][3] memory) {
      return foo;
    }

    function getFooByIndex(uint i) public view returns(uint8[] memory) {
      return foo[i];
    }
}
2
  • Doesn't uint8[3][] declare a variable array where elements are arrays of fixed length 3? I want the opposite case, a fixed array of size 3, where each element is a variable sized array. I think that should be possible in the EVM storage model.
    – Ivan Voras
    Mar 28, 2023 at 22:43
  • I'm not entirely sure what your specific goal is, but I edited my answer hope that helps
    – Adam Boudj
    Mar 29, 2023 at 9:09

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.