Dynamic Arrays
A dynamic-sized array in solidity can grow and shrink in size, the behavior is different when the array is in storage or memory.
- The
storagedynamic array does not need to declare the size at initialization since we can grow or shrink the array later.
contract StorageDynArray {
uint[] public arr; // dynamic array in storage
}- The
memorydynamic array act like a fixed sized array, we need to declare the size at initialization.
contract MemoryDynArray {
function f() public {
// dynamic array in memory with initial length 5
uint[] memory arr = new uint[](5);
}
}Important
The
pushandpopmethods are only available for dynamic arrays instorage, not inmemory. Even though from the type signature ofuint[] arr, it looks like a dynamic array, but compiler treats it as a fixed sized array inmemory.
Getter
To reduce the gas cost, the getter function of array types only provide access to individual elements, not the whole array.
contract Alice {
uint[] public arr;
}
contract Bob {
function f() public view returns (uint) {
Alice alice = new Alice();
return alice.arr(0); // access the first element of the array
}
}