0

I want to create a temporary array that is returned from a function. I declare it in the function and use the memory tag but I am unable to push to it.

function getAllLandForSale() external returns(uint256[]){

        uint[] memory propertiesForSaleArray;

        // Get the total number of properties created
        uint256 totalNumberOfProperties = baseContract.getLandArrayLength();

        for(uint i = 0; i < totalNumberOfProperties; ++i) {

           address currentOwner = baseContract.getLandOwner(i);

           if(currentOwner == address(0)){

               propertiesForSaleArray.push(i);

           }

        }
    }

I am getting the following error.

enter image description here

  • 1
    Seems like you can still do propertiesForSaleArray[i] = i; – Roman Frolov Jan 15 '18 at 23:50
  • If I do that will there be gaps in the returned array where the address is not 0 for example array[value,empty,empty,value,value]? I was looking for something like [value,value,value] etc. – ORStudios Jan 15 '18 at 23:58
  • yes, but you can avoid them by adding simple counter which will increase its own value only when new element is added to the array. – Roman Frolov Jan 16 '18 at 0:01
  • Sorry you have lost me with that bit of advice, not sure what you mean by a counter will increase its own value. – ORStudios Jan 16 '18 at 0:04
2

Summarizing what I tried to say in comment section below the question:

uint c = 0; // counter

for(uint i = 0; i < totalNumberOfProperties; ++i) {

   address currentOwner = baseContract.getLandOwner(i);

   if(currentOwner == address(0)){

      propertiesForSaleArray[c] = i;

      c = c + 1;

      // this will only add propeties for sale to your array, without the gaps
   }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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