Solidity – How to Initialize a uint16[] Array

arrayssolidity

I have a hard time creating a uint16[] array in an elegant way.

I try this:

function init() public {
uint16[] memory x = [uint16(1), uint16(1)];
test(x)
}

This raises TypeError: Type uint16[2] memory is not implicitly convertible to expected type uint16[]

I want to use this initialized array in a

function test(uint16[] input){}

function

I can of course create a uint16[] array and the push values in it, but this is not an elegant way of initializing it. How do I correctly initialize these values?

Best Answer

With the current version of Solidity (v.0.4.21), fixed size memory arrays cannot be assigned to dynamically-sized memory arrays.

Check out the documentation on Array Literals / Inline Arrays in the Solidity documentation.

The following code will not work:

// This will not compile.

pragma solidity ^0.4.0;

contract C {
    function f() public {
        // The next line creates a type error because uint[3] memory
        // cannot be converted to uint[] memory.
        uint[] x = [uint(1), 3, 4];
    }
}

The documentation says:

It is planned to remove this restriction in the future but currently creates some complications because of how arrays are passed in the ABI.