0

I am currently playing around with Solidity and dynamic arrays. I have the following code:

contract Test{
    int256[] public test;

    function setTest(int256 b) public{
        test.push(b);
    }

    function setTest2(uint256 a, int256 b) public {
        test[a] = b;
    }
}

I executed the code in remix. When I call setTest(1) and call the getter test(0), the output is 1. If I do the same with setTest2(0, 1) and call the getter afterwards, the value does not seem to be saved. I don't understand why. Could someone explain what is going on here?

Thanks in advance.


I realized that my question is not really clear and I will ask the question here and this time more clear. Thanks for the other answers already.

I call the function setTest2(0, 1) and call the getter afterwards, remix shows me that the value at position 0 is 0 and not 1. When I call the setTest(2) function and call the getter afterwards, the value 2 is at position 0 of the array and not at position 1. This means that the value of the first call has not been saved. Why?

3
  • If you call setTest2(0,1) on an array of a length of 0, it won't work. Commented Apr 27, 2018 at 15:10
  • It's length is 0? How come? Is it somewhere in the docs? I can't find it...
    – Donut
    Commented Apr 27, 2018 at 15:12
  • If you didn't push anything before, yeah, your array is empty, and trying to set some value at whatever position will fail Commented Apr 27, 2018 at 15:15

3 Answers 3

3

When using Dynamic arrays, you can't use DynamicArray[a] = b, if position a is not yet filled by the push function. If it would be a Static array, then it would work.

0
0

When you call setTest(1), your array contains 1 at the position 0. After that, you call setTest2(0,1), which sets at the position 0 the value 1.

The value is the same, so you won't notice any difference. If you call setTest2(0,5), you will see it will be different.

1
  • Thanks and it makes sense. I realized that my question did not cover the initial question. I edited it.
    – Donut
    Commented Apr 27, 2018 at 15:05
0

Regarding your edit.
I just checked and it seems that calling setTest() on a position of the array, that hasn't been initialized previously doesn't work. So in otherwords, you can use that to change a value, but not add a new one.
That's why your setTest() always starts at the beginning. You first need to push a new element to a position in order for setTest2() to have any effect.

1
  • Yea, you are right and it makes sense. I realized that my question did not cover the initial question. I edited it.
    – Donut
    Commented Apr 27, 2018 at 15:06

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.