[Ethereum] How to initialize an empty array and push items into it

arrayssolidity

Here's my function:

function Test() constant returns (uint[]) {
   var myArray = uint[];
   myArray.push(123); 
   return myArray;
}

Here's an error I get in the solidity online compiler:

ballot.sol:25:9: Error: Member "push" not found or not visible after argument-dependent lookup in type(uint256[] memory)
myArray.push(123);

Best Answer

You need to use an array in storage because it is not possible to resize memory arrays.

contract D { 
    uint[] myArray;
    function Test() constant returns (uint[]) {
       myArray.push(123); 
       return myArray;
    }
}

Otherwise you need to define the size of the array during initialization:

contract C {
    function f(uint len) {
        uint[] memory a = new uint[](7);
        bytes memory b = new bytes(len);
        // Here we have a.length == 7 and b.length == len
        a[6] = 8;
    }
}
Related Topic