1

I am trying to assign the value of a matriz to two arrays as follows:

pragma solidity ^0.4.24;
pragma experimental ABIEncoderV2;

contract ArrayExamples {

    int[][] public matriz;


    // Os dados são recebidos da seguinte forma: [0,0]
    function receive_data(int[] data) public {
        matriz.push(data);
    }


    function teste() public returns (int[] v) {

        int[] x;
        int[] y;

        uint t = matriz.length;

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

            x[i] = matriz[i][0];
            y[i] = matriz[i][1];

        }

        return x;
    }

  }

The array is dynamic, but in the example above defaults to an array with two elements. [0.0]

When I assign the values ​​of x and y in for, only the values ​​of y are assigned correctly. x is responsible for taking only the first value from the dynamic array of the matrix and y takes the last value.

When I check the value of x, it appears that he took the last value from the dynamic array, and he should get the first value from the array.

If I enter the following array: [4,5] - both x and y get 5, where x should get 4.

1

You are using solidity v0.4 I'd suggest to use v0.5 instead

In solidity v0.4 the following generates a warning because x and y are not initialized.

function teste() public returns (int[] v) {
    int[] x;
    int[] y;

}

They don't have memory modifier so they refer to storage. They are not assigned a slot so by default they refer to slot 0 on storage which is used by matriz.

Your function in solidity 0.5 can be implemented like this:

function teste() public view returns (int[] memory v) {
    // allocate in memory
    int[] memory x = new int[](matriz.length);
    int[] memory y = new int[](matriz.length);

    uint t = matriz.length;
    for(uint i = 0; i < t; i++) {
        x[i] = matriz[i][0];
        y[i] = matriz[i][1];
    }
    return x;
}
| improve this answer | |

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.