Search code examples
ethereumsolidity

How to set array size in return by array input in Solidity?


How in solidity to set the fixed length of returned array, according to the array in parameters?

 // For example I have this simple function, which convert array uint to int 

 // but this not works, because dynamic length array
 function convertUintToInt(uint[] _input) public pure returns(int[] _output){
     for(uint i = 0; i < _input.length; i++){
         _output[i] = int(_input[i]);
     }

    return _output;
  }



 // this works for length 10, but if input.length < 10 this return unnecessary empty items
 // if _input.length > 10 this will not works
 function convertUintToInt(uint[] _input) public pure returns(int[10] _output)



 // I need just something like this 
 function convertUintToInt(uint[] _input) public pure returns(int[_input.length] _output)

Main goal not use storage!

I just need create readable contract helper for convert data


Solution

  • pragma solidity ^0.5.12;
    
    contract Ballot {
        function convertUintToInt(uint256[] memory _input) public pure returns(int[] memory){
        int[] memory tmpArr = new int[](_input.length);
         for(uint i = 0; i < _input.length; i++){
             tmpArr[i] = int(_input[i]);
         }
    
        return tmpArr;
      }
    }