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 storage dynamic 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 memory dynamic 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 push and pop methods are only available for dynamic arrays in storage, not in memory. Even though from the type signature of uint[] arr, it looks like a dynamic array, but compiler treats it as a fixed sized array in memory.

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
    }
}