Index
Array Pushing
pragma solidity >=0.4.22 <0.7.0;
contract ArrayPushing {
uint[] myarray = new uint[](0);
function pushTheArray (uint len) public {
myarray.push(len);
}
function getTheArray() public view returns (uint[] memory) {
return myarray;
}
}
contract ArrayPushing {
uint[] myarray = new uint[](0);
function pushTheArray (uint len) public {
myarray.push(len);
}
function getTheArray() public view returns (uint[] memory) {
return myarray;
}
}
getTheArray
Output:
0: uint256[]:
See the output is empty
pushTheArray(5)
getTheArray
output:
0: uint256[]: 5
pushTheArray(10)
getTheArray
0: uint256[]: 5,10
Twisted code:
pragma solidity >=0.4.22 <0.7.0;
contract ArrayPushing {
uint[] myarray = new uint[](5);
function pushTheArray (uint len) public {
myarray.push(len);
}
function addElementToIndex(uint index, uint data) public {
myarray[index] = data;
}
function getTheArray() public view returns (uint[] memory) {
return myarray;
}
}
contract ArrayPushing {
uint[] myarray = new uint[](5);
function pushTheArray (uint len) public {
myarray.push(len);
}
function addElementToIndex(uint index, uint data) public {
myarray[index] = data;
}
function getTheArray() public view returns (uint[] memory) {
return myarray;
}
}
getTheArray
output:
0: uint256[]: 0,0,0,0,0
See it has 5 elements
pushTheArray(5)
getTheArray
output:
0: uint256[]: 0,0,0,0,0,5
Now it has 6 elements
addElementToIndex(5,22)
getTheArray
output:
0: uint256[]: 0,0,0,0,0,22
addElementToIndex(1, 101)
getTheArray
output:
0: uint256[]: 0,101,0,0,0,22
addElementToIndex(10, 101010)
Result:
invalid opcode