Created
February 28, 2019 22:41
-
-
Save gdebenito/db23f979f708b2904d54697672707a66 to your computer and use it in GitHub Desktop.
How does solidity stores dynamic arrays in a ethereum smart contract?
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
pragma solidity >=0.4.22 <0.6.0; | |
contract DynamicArray { | |
uint256[] store; | |
function getAssembly(uint256 _idx) external view returns(uint256 _value) { | |
bytes32 dir = keccak256(abi.encodePacked(uint256(0))); // stored at slot 0 | |
assembly{ | |
_value := sload(add(dir,_idx)) // access to keccak256 of slot 0 plus offset | |
} | |
} | |
function get(uint256 key) external view returns(uint256) { | |
return store[key]; | |
} | |
function set(uint256 _value) external { | |
store.push(_value); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment