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.
}
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.
}
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
uint8[5][5] memory myArr;
might do the trick.
– Jasper
Jul 1 '17 at 13:22
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.