In Solidity, how do I define a fixed size, 2 dimensional uint8 array scoped to a function, initialized with all zeros?


  var myArr = new uint8[5][5](); // which does not work.

2 Answers 2


Declaring an array inside a function is allocating a Memory Array which is different than storage array. Source

new is used to declare variable sized array so I would do

function getValue(uint8 x, uint8 y) constant returns (uint8) {
    var length = 5;
    uint8[5][5] memory myArr;
    for (uint i = 0; i < length; i++)
        for (uint j = 0; j < length; j++)
            myArr[i][j] = 0;

    return myArr[x][y];

You can test this on Remix to see that it works

  • 1
    So if I wanted to have an array uint8[256][256] I would have to type 65536 zeros?
    – Jasper
    Jul 1, 2017 at 13:19
  • 1
    Ah, but your link is helpful. It seems uint8[5][5] memory myArr; might do the trick.
    – Jasper
    Jul 1, 2017 at 13:22
  • 1
    Well I had weird issue when trying to do a loop to initialize it. But I'm pretty sure it is possible to do so. Jul 1, 2017 at 13:30
  • 1
    @Jasper I edited my post to initialise array with loops Jul 3, 2017 at 8:52

The solution is using the memory keyword:

uint8[4][2] memory myArr;

myArr will then return the default value uint8(0) for all indices.

It should also be noted, that in Solidity array size is defined in reverse lookup order. The last number in myArr would thus be uint[1][3].

Also, in memory Arrays, uint8 may actually be more costly than just using uint256, since the latter is used internally.

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.