2

pragma solidity ^0.4.18;

contract VectorTest {

   /* this runs when the contract is executed */
   function VectorTest() public {
      // initialize the variables        
   }

   // returns an int array by adding to all its elements a scalar value "a"
   function addScalar(int[] self, int a) public pure returns (int[] s) {
      for (uint i = 0; i < self.length; i++)
         s[i] = self[i] + a;
  }

   // returns an int array by adding to all its elements a scalar value "a"
   function addVector(int[] self, int[] melf) public pure returns (int[] s) {
      for (uint i = 0; i < self.length; i++)
         s[i] = self[i] + melf[i];
   }

}

I have a very basic VectorTest contract as above. It compiles well in Remix but when I create and try to call its functions with some example values, Remix is giving the error below. E.g., I tried to execute addScalar([12,12,13], 5) in this error message:

call to browser/BlockChaiNergy01.sol:BlockChaiNergy01.addScalar 
errored: VM error: invalid opcode.
invalid opcode  The constructor should be payable if you send value.
The execution might have thrown.
Debug the transaction to get more information. 

Any ideas?

Thanks in advance,

Onder.

1 Answer 1

4

You are not allocating the returned array s

function addScalar(int[] self, int a) public pure returns (int[] s) {

    // Allocate s
    s = new int[](self.length);

    for (uint i = 0; i < self.length; i++)
        s[i] = self[i] + a;
    }
}

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.