44

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

2 Answers 2

64

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;
    }
}
4
  • 1
    Oh, I get it now, thank you for your time and knowledge!
    – manidos
    Jan 20, 2017 at 9:02
  • 1
    It was so simple I completely missed it Sep 30, 2017 at 6:36
  • 6
    If we need a memory array inside a function, but wen don't know the items count, what can we do? Thank you!
    – Suge
    Dec 24, 2017 at 5:50
  • 4
    @Suge I suggest asking a separation question with more details and be careful to avoid meta.stackexchange.com/questions/66377/what-is-the-xy-problem
    – eth
    Dec 30, 2017 at 13:52
3

You could define the array with the length of the array you want to filter. Problem is all the tail of empty elements.

uint[] memory filteredArray = new uint[](fullArray.length);
a[0] = 1;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.