Arrays

Fixed Length Arrays

  • Under the hood, will behave like structs

function fixedArray() external {
        bytes32 x40;
        assembly {
            x40 := mload(0x40)
        }
        emit MemoryPointer(x40); // 0x80 
        uint256[2] memory arr = [uint256(5), uint256(6)];
        assembly {
            x40 := mload(0x40)
        }
        emit MemoryPointer(x40); // 0xc0
    } 
// 0xc0 - 0x80 = 64 bytes 

Dynamic Length Arrays

  • To access a dynamic array, we have to add 32 bytes (or 0x20) to the memory location to skip the location that stores length of the array, and read the first item

function args(uint256[] memory arr) external {
        bytes32 location;
        bytes32 len;
        bytes32 valueAtIndex0;
        bytes32 valueAtIndex1;
        assembly {
            location := arr
            len := mload(arr)
            valueAtIndex0 := mload(add(arr, 0x20))
            valueAtIndex1 := mload(add(arr, 0x40))
            // ...
        }
        emit Debug(location, len, valueAtIndex0, valueAtIndex1);
    }
// if array = [4, 5]: 
// location: 0x80
// length: 0x2 
// valueAtIndex0 = 0x4
// valueAtIndex1 = 0x5 

Gotchas

Last updated