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)];

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){}


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?

  • 1
    In which scope is the line uint16[] memory = [uint16(1), uint16(1)];? Apr 25 '18 at 22:12
  • 1
    It is in a public function. I'll edit my question.
    – JBrouwer
    Apr 25 '18 at 22:12

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.

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.