I need to add elements to a resizable myArray
and then delete the myArray
. I don't know what the length of myArray
will be before the loop, and it's not possible to resize a memory array; that leaves me with a storage array.
In v0.6.0
a breaking change was made to make member-access to length
of arrays always read-only, so I can no longer simply call myArray.length = 0
to effectively delete the array. And calling delete myArray
throws the compilation error: TypeError: Unary operator delete cannot be applied to type uint256[] storage pointer
.
pragma solidity 0.6.0;
contract Hello {
function withdraw() external {
uint256[] memory blocktimes = getBlocktimes();
uint256[] storage myArray;
for (uint256 i = 0; i < blocktimes.length; i++) {
if (blocktimes[i] <= block.timestamp) {
// do something
} else {
myArray.push(blocktimes[i]);
}
}
if (myArray.length > 0) {
// assign myArray to something else, then...
delete myArray;
}
}
}
Also, the blocktimes
array is bounded, so please save the "anti-pattern" pestering :) I'm simply asking how I can append elements to a resizable array, and then delete it.
blocktimes
array is not even shown in your question. Please add it in order to make the code an MVP (at least for solc 0.5.x).uint256[] storage myArray;
inside a function. First, It's not really clear from your question why you need to allocate this array when you immediately delete it at the end. It is also not really clear why this is a storage array and not a memory array to begin with. A storage variable in a function must be initialized to point to (reference) some state variable which actually resides in storage. You don't have such state variable in your code, and you are (subequently) not initializing your local storage variable to point to such a state variable.uint256[] memory myArray = new uint256[](blocktimes.length);
, thenuint256 j = 0;
before the loop, and thenmyArray[j++] = blocktimes[i];
inside the loop.uint256[] storage myArray;
is exceptionally dangerous. blog.b9lab.com/storage-pointers-in-solidity-7dcfaa536089#9955