Skip to content

Instantly share code, notes, and snippets.

@gdebenito
Created February 28, 2019 22:41
Show Gist options
  • Save gdebenito/db23f979f708b2904d54697672707a66 to your computer and use it in GitHub Desktop.
Save gdebenito/db23f979f708b2904d54697672707a66 to your computer and use it in GitHub Desktop.
How does solidity stores dynamic arrays in a ethereum smart contract?
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