1

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...

2
  • 1
    Could you provide more code for how the contract works? If tmp is in the global scope, for example, you wouldn't need the storage pointer. And if the array inside the contract will always be used with the xyz, then you could just call directly in your function without passing it as an argument.
    – Alex Otsu
    Jun 22, 2021 at 17:07
  • Hi @AlexOtsu, I just updated the question to better explain what I am trying to do.. is it possible or any alternative solution to do this? Jun 24, 2021 at 8:57

1 Answer 1

2

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);
    }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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