DEV Community

Loading Blocks
Loading Blocks

Posted on

Solidity Arrays

Preface

In Solidity, there are two kinds of arrays:

  1. Fixed-size array:

    You must specify array length at declaration time.

    Example: uint[5] numbers;

    Once created, the length is not possible to change.

  2. Dynamic-size array:

    No need to specify length at declaration.

    Example: uint[] numbers;

    The length can be changed at runtime (grow or shrink).


Most common syntax

uint[5] numbers;                     // fixed size array
uint[] numbers;                      // dynamic array
numbers[i];                          // access by index
uint[] storage refToNumbers = numbers; // storage reference
function f(uint[] memory a) external { ... } // pass memory array
numbers.push(x);                     // append to end
numbers.pop();                       // remove the last element
uint n = numbers.length;             // get length
delete numbers[i];                   // reset value to default
for (uint i = 0; i < numbers.length; i++) { ... } // loop
Enter fullscreen mode Exit fullscreen mode

Memory Arrays

When declaring an array inside a function, you must use the memory keyword.

A memory array always have fixed size, so you cannot call push or pop.

You can use the new keyword to create a memory array based on a variable size.

Example:

function createMemoryArray(uint size) public pure returns (uint[] memory) {
    uint[] memory newArr = new uint[](size);
    return newArr;
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)