4

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?

  • did you try just uint8[12] memory traits; ? – Achala Dissanayake Oct 9 '17 at 2:06
  • 1
    You are right @AchalaDissanayake ! Can you put that as an answer? – Fabiano Soriani Oct 11 '17 at 20:05
6

To initialize an empty array instead of in solidity 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;
}
5

In order to initialize an array from memory you have to do it like this:

uint8[] memory theArray = new uint8[](12) 

Where the 12 inside the parenthesis is the array length.

You can also initialize the array as follows:

function getTraits() constant returns (uint8[3]){
      uint8[3] memory traits = [1,2,3];
      return traits;
    }
  • 1
    My question is to init uint8[12], this solution errors to return: TypeError: Return argument type uint8[] memory is not implicitly convertible to expected type (type of first return variable) uint8[12] memory. return traits; – Fabiano Soriani Oct 8 '17 at 23:45
  • 1
    You have to change the function's return type to uint8[] to fix that. Alternatively, you could initialize de fixed-size array like I just wrote in my updated answer. – pabloruiz55 Oct 9 '17 at 0:02

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.