Below i will describe how the storage layout in a contract looks like for a dynamic array:
Array Length: The length of the array is stored in the assigned storage slot for the array variable.
Array Elements: The elements are stored starting from a computed slot based on the hash of the array’s base slot.
Let’s explore this in detail
1. Array Length Storage
Solidity uses the assigned storage slot of the array variable to store its length.
This slot is the first point of reference for determining the storage layout.
If the array is defined at storage slot 0 (when it is the first state variable), the slot 0 represents the length of the array
2. Array Elements Storage
The actual elements are stored starting from a calculated offset derived from the keccak-256 hash of the base slot.
The formula for determining the slot where the elements start is:
Array Length: The length of the array is stored in the assigned storage slot for the array variable.
Array Elements: The elements are stored starting from a computed slot based on the hash of the array’s base slot.
Let’s explore this in detail
1. Array Length Storage
Solidity uses the assigned storage slot of the array variable to store its length.
This slot is the first point of reference for determining the storage layout.
If the array is defined at storage slot 0 (when it is the first state variable), the slot 0 represents the length of the array
2. Array Elements Storage
The actual elements are stored starting from a calculated offset derived from the keccak-256 hash of the base slot.
The formula for determining the slot where the elements start is:
Each element in the array occupies 32 bytes (1 storage slot), stored in consecutive slots starting from keccak256(p).