If the array is located in memory, then all the elements are in sequence, for example:
uint256 arrLength = arr.length;
assembly{
let offset := sload(arrLength)
res:= mload(add(arrLength,0x20)) //first element
}
But I don’t understand how in the arrays located in the storage? the keys of the elements are generated?
How to get a pointer to an array located in storage?
How to get the value of an element knowing its index?
Best Answer
Each storage variable has its own storage slot whose address is a sequential number of this variable within contract:
For atomic variables, such as
x
, this slot holds variable value.For mapping variables, such as
y
, this slot is not used, but still allocated.For dynamic array variables, such as
z
, this slot contains array length.Array data is stored separately in consequent storage slots starting from the slot with address
keccak256 (n)
wheren
is variable sequential number.So, to access array
z
declared above, you may use the following assembly:Of cause,
keccak256 (2)
should not be calculated every time, such should be substituted as compile-time constant.See documentation for more details.