[Ethereum] Error ; Member “push” is not available in address[] memory outside of storage

arrayssolidity

I am writing a function to generate trail of all address who owned an asset ( assets is a mapping of asset no to owner no to address of owner).
However while making array of address 'listofOwners' I get compilation error, Member "push" is not available in address[] memory outside of storage.

function viewTrail(uint256 _assetNo) public view returns(address[] memory){
   address[] memory listofOwners = new address[](assets[_assetNo].ownerNo);
  for(ownerNo = 1; ownerNo<= assets[_assetNo].ownerNo; ownerNo ++)
  {
  listofOwners.push(owneraddr[_assetNo][ownerNo]);
  }

return listofOwners;}

Can you please suggest a solution or some other code to generate trail of owners of an asset?

Best Answer

You can assign the elements to the array position by referencing the element key like myArray[0] = ‘new value’;

The following example uses a view function, because the array is in memory:

function getMultipleAddresses( string[] calldata ids) public view returns (address[] memory) {

    address[] memory _addresses;
    
    for (uint256 i = 0; i < ids.length; i++) {
      string memory id = ids[i];
      require(_idToAddress[id] != address(0), 'Missing address');
      address payable _address = payable(_addresses[i]);

      _addresses[i] = _address;
    }