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
.