Member "push" is not available in bool[] memory outside of storage

Viewed 3850

I was trying a simple push operation within solidity. As shown in the code below with function isArrayEven():

pragma solidity ^0.8.12;

contract Test {
    uint[] public arr = [uint(1), 2, 3, 4, 5, 6, 7, 8 ,9];

    function isArrayEven() public view returns(bool[] memory) {
        bool[] memory ret;

        for (uint i = 0; i < arr.length; i++) {
            ret.push((arr[i]%2 == 0));
        }

        return ret;
    }
}

But the following error is thrown:

Member "push" is not available in bool[] memory outside of storage.

I have figured out how to fix this by using below:

pragma solidity ^0.8.12;

contract Test {
    uint[] public arr = [uint(1), 2, 3, 4, 5, 6, 7, 8 ,9];

    function isArrayEven() public view returns(bool[] memory) {
        bool[] memory ret = new bool[](arr.length);

        for (uint i = 0; i < arr.length; i++) {
            ret[i] = (arr[i]%2 == 0);
        }

        return ret;
    }
}

But I don't understand this behavior, why is 'push' not allowed for memory arrays?

1 Answers

Memory arrays with dynamic length can be created using the new operator. As opposed to storage arrays, it is not possible to resize memory arrays (e.g. the .push member functions are not available). You either have to calculate the required size in advance or create a new memory array and copy every element. https://docs.soliditylang.org/en/v0.8.12/types.html#allocating-memory-arrays

Related