Dynamic Arrays

The Cooler Version of Static Arrays

Recall in Data Structures that we can declare a static array as follows:

T[] arrayName = new T[](n);

where T is the type of the array. The good news is that defining a dynamic array is not that much different; below is the syntax for declaring a dynamic array:

T[] arrayName;

Declaring a dynamic array seems simple, but what about defining a dynamic array? Below is the syntax to define a dynamic array:

T[] arrayName = [] // Insert array elements here

Since dynamic arrays can vary in size, we would ideally like to have functions available to us which allow us to grow/shrink our array. And indeed, Solidity provides us with such functions.

  • array.push(x): pushes x to the back of array

  • array.pop(): pops the last element of array

And like with static arrays, we can also index into dynamic arrays; it should be noted, however, that this can cause runtime errors if the user is attempting to index into an undefined location of a dynamic array.

Dynamic Arrays in Memory?

As with mappings, dynamic arrays are reserved only for state variables; one cannot declare/define a new dynamic array variable within a function.

Last updated