Arrays in Solidity

Published by Mario Oettler on

Arrays store a collection of elements of the same data type. They are accessible by their index.

The first row shows the index starting with 0. The second row shows the values. Here, they are of type string.

In Solidity, arrays can be defined in storage or memory. However, only storage arrays can be dynamically sized. Memory-based arrays are always fixed-sized.

Storage Arrays

Storage arrays are defined either in a fixed length or a dynamic length.

Fixed-size array of length 10:

uint256[10] myFixedArray;

Dynamic size array:

uint256[] myDynamicArray;

Adding a value can be done in two ways. First, adding a value to a certain index:

myArray[1] = “Hello World”;

or by using push() to append a value to an array.

Defining a Memory Array

uint[] memory myMemoryArray = new uint[](7);

This memory array has the length 7.

Memory arrays cannot be extended during runtime. The member function push does not exist.

If you need to resize your memory array, you need to create a new array with the desired length and copy every element from the old array.