When Storing Dynamic type data , We don’t explicitly store the data in the next immediate slot, instead we only store the address of the slot where the element of that index is , In simpler words we are basically storing the “Pointer” to the actual address and through the Pointer we can access the referred slot where the element actually resides.
contract Demo {
uint256 a = 0x1a01; //slot 0
uint256 b = 0x2a01; // slot 1
uint256[] c; // slot 2
uint256 d = 0x5a01; // slot 3
contructor(){
c.push(0xb);
c.push(0xef2134);
c.push(0x2342)
}
function getArrayElementSlot(uint index,uint storedSlot) public pure returns(uint256)
{
// Line 13
uint arrayElementSlot = uint256(keccak256(abi.encodePacked(storedSlot))) + index ;
return arrayElementSlot;
}
function getSlotvalue(uint slot) public view return(bytes32) //Line 15
{
bytes32 value;
assembly{
value := sload(slot);
}
return value;
}
}
Okay now let’s understand what is actually happening to store Dynamic data type , As you can see the Array “ c ” is a dynamic uint array.
In the Constructor we store 3 elements in the array “ c “ , also Array “ c ” is allotted with slot-2 but it is a dynamic array . So it will not store the elements of array , Instead it will only store length of the array .
Now to retrieve the elements , it is a 2-step process
Retrieve the slot address of the element
Retrieve the element from the slot address received from step-1
In Line 13 we are following step-1 , which is to retrieve the slot address , we basically provide the slot of Array “c” which is a 2 and the index of element , we want to retrieve . For example we want the element at index 0 , in Line 13 we apply the keccak256 hashing algorithm and add the the index as a result we receive the Slot-Number of element at index 0 , next we follow step-2 and provide the slot Number to getSlotValue function in Line 15 and it gives us the exact element stored in the slot.