Solidity – Initialize Memory Array of Fixed Size

arrayscontract-debuggingcontract-developmenterrorsolidity

Using solidity 0.4.15, there is a function that takes a number and returns array of fixed length called traits:

function splitN(uint256 n) constant returns (uint8[12]) {
    uint8[12] memory traits = new uint8[12];
    // alter values in traits ...
    return traits;
}

But this way to initialize traits don't compile, with the errors:

.../Genes.sol:28:39: TypeError: Length has to be placed in parentheses after the array type for new expression.
        uint8[12] memory traits = new uint8[12];
                                      ^-------^
,.../Genes.sol:28:9: TypeError: Type function (uint256) returns (uint8[12] memory) is not implicitly convertible to expected type uint8[12] memory.
        uint8[12] memory traits = new uint8[12];

Then I tried following the message hints, and a bunch of other ways to initialize, but the only way I could make it work was to actually fill an array of 12 zeroes:

    uint8 z = 0;
    uint8[12] memory traits = [z, z, z, z, z, z, z, z, z, z, z, z];

So is there a more elegant way of initializing the array?

Best Answer

To initialize an empty array instead of uint8[12] memory traits = new uint8[12]; use uint8[12] memory traits;.

Then you can alter the array in the // alter values in traits ... section.

function splitN(uint256 n) constant returns (uint8[12]) {
    uint8[12] memory traits;
    // alter values in traits ...
    return traits;
}