What are arrays in Solidity?
An array is a collection of elements of the same type stored in memory, e.g., a list of people’s ages.
In Solidity, the size of the array can be fixed or dynamic.
Syntax for array declaration
dataType[size] arrayName = <elements>;
dataType: The data type of the elements present in the array. It should be a valid Solidity data type.arrayName: The name of the array.size: The size of the array. It should not be predefined in the case of a dynamic-size array.elements: The elements of the array.
Example 1
In the code snippet below, we create a fixed-size array.
pragma solidity ^0.5.0;contract fixedArray {// declare a fixed size arrayint[5] data;// function to populate arrayfunction populate() public returns (int[5] memory) {data = [9, 2, 8, 4, 6];return data;}}
Explanation
In the code snippet above:
-
Line 3: We create a contract-type
fixedArray. -
Line 5: We declare a fixed-size array
dataof integer type and give it a size of5. -
Line 8: We create a function
populate. -
Line 9: We initialize the
dataarray with some elements. -
Line 10: We return the
dataarray.
Note: Since the
dataarray is a fixed-size array of length five, an error will be thrown if we try to add more than five elements.
Example 2
In the code snippet below, we create a dynamic-size array.
pragma solidity ^0.5.0;contract dynamicArray {// declare a dynamic size arrayint[] data;// function to populate arrayfunction populate() public returns (int[] memory) {data = [9, 2, 8, 4, 6, 1, 10];return data;}}
Explanation
In the code snippet above:
-
Line 3: We create a contract-type
dynamicArray. -
Line 5: We declare a dynamic-size array
dataof integer type. As discussed earlier, we will not predefine the size of the array inside the[]. -
Line 8: We create a function
populate. -
Line 9: We initialize the
dataarray with some elements. -
Line 10: We return the
dataarray.
Note: Since the
dataarray is now a dynamic-size array, we can add as many elements as we want.