solidity – How to Copy All Items of an Array to a Different Size Dynamic Array in Contract Development

arrayscontract-developmentsoliditystorage

I have a problem when I try to store an array in another array. I get as error when running store: transact to MyContract.store errored: VM error: revert.

I need the second array, because in the next step I want to push more values to it (_arr.push()). But I get errors already during compilation (TypeError: Member "push" is not available in address[] memory outside of storage.).

Therefore I create _arr directly with a length: uint256[] memory _arr = new uint256[](myVal.length+1); and then store the new value directly to the last position (_arr[_arr.length-1] = 42;) (I left this out in the example below, because it already doesn't work without this line!).

Does anyone have any idea what I'm currently missing, or if there is an alternative approach?

// SPDX-License-Identifier: MIT

pragma solidity >=0.6.0 <0.9.0;

contract MyContract {
    uint256[] myVal;
    uint256[] _arr;

    function store(uint256 _myVal) public {
        myVal.push(_myVal);
        for(uint256 _y = 0; _y < myVal.length; _y++){
            _arr[_y] = myVal[_y];
        }
    }
    function retrieve() public view returns (uint256[] memory) {
        return _arr;
    }
}

Thanks already in advance 🙂

Best Answer

I didn't quite understand the depth of the idea, but maybe this option will help:

    function store(uint256 _myVal) public {
        myVal.push(_myVal);
         
        for(uint256 _y = 0; _y < myVal.length; _y++) 
            if(_y<_arr.length)
                _arr[_y]=myVal[_y];
            else
                _arr.push(myVal[_y]);
    }
Related Topic