1

How to update an element in a dynamic array by a specific index?

I know how .push() property works for a dynamic array but I am trying to add an element providing an index so the transaction reverted with no explanation.

contract TestArray { 
   uint[] public id;

   function updateByIndex(uint _id, uint _index) public {
        id[_index] = _id;
   }

1 Answer 1

2

The code you provided should never work since it would always fail the Solidity bounds checks which assert that the _index your are trying to access should be less than the length of the array. Arrays in Solidity differ from mappings, as they are tied to a length parameter that gets incremented everytime you push new elements to the array.

In previous versions of Solidity (i.e., v0.5.x), it used to be the case that the length parameter of an array was writable. The following code would've worked:

pragma solidity 0.5.x;

contract TestArray { 
   uint[] public id;

   function updateByIndex(uint _id, uint _index) public {
        if (_index + 1 > id.length) {
            id.length = _index + 1;
        }
        id[_index] = _id;
   }
}

The code above basically increments length conditionally so that the array index you are trying to access is always less than length and the code doesn't revert due to bound checks.

But at the time of writing with Solidity v0.8.x, this is no longer the case. The length parameter is currently read-only, and the only way to increment it would be to append new elements to the array via push.

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.