3

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

E.g.

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

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 '17 at 13:19
  • 1
    Ah, but your link is helpful. It seems uint8[5][5] memory myArr; might do the trick. – Jasper Jul 1 '17 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. – Crema Jul 1 '17 at 13:30
  • 1
    @Jasper I edited my post to initialise array with loops – Crema Jul 3 '17 at 8:52
1

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, privacy policy and cookie policy

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