Solidity – How to Pass an Array as Argument to a Function

solidity

I am trying to pass an array as an argument and I don't know the correct way.

The function looks like as given below:

contract A {
    function xyz(uint256[] memory amounts){
        uint value1 = amounts[0];
        uint value2 = amounts[1];
    }
}

and I am trying to pass argument as shown below:

contract B is A {
    uint count = 1;

    function passArg(){
        uint[] memory  tmp;
        tmp.push(count);
        count = count + 1;
        tmp.push(count);
        xyz(amounts);
    }
}

This gives me an error invalid opcode

Best Answer

Memory arrays don't have the ".push(...)" method available, since that method is only available for dynamic storage arrays and you can't have dynamic memory arrays. You will need to either change the tmp array into a storage array as follows:

contract B is A {
    uint count = 1;
    uint[]  tmp;

    function passArg(){
        tmp.push(count);
        count = count + 1;
        tmp.push(count);
        xyz(tmp);
    }
}

Or, keep it as a memory array and initialize it to a fixed size as follows:

contract B is A {
    uint count = 1;

    function passArg(){
        uint[] memory  tmp = new uint[](2);
        tmp[0] = count;
        count = count + 1;
        tmp[1] = count;
        xyz(tmp);
    }
}