- There are two type of arrays:
1. Fixed Sized Array:
- The size of an array is defined at the creation of the array
- cannot be resized after creation of array
- e.g
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.7.0 <0.9.0;
contract FixedSizedArray {
uint[3] nums;
function add(uint _num1, uint _num2, uint _num3) public {
nums[0] = _num1;
nums[1] = _num2;
nums[2] = _num3;
}
function search(uint _index) public view returns (uint) {
require(_index < 3, "this is a 3 indexed fixed array");
return nums[_index];
}
function array() public view returns (uint256[3] memory){
return nums;
}
}
2. Dynamic Array:
- The sized of array is dynamic i.e it can be changed dynamically at execution time.
- e.g
contract DynamicArray{
uint[] nums;
function addNumber(uint _num) public {
nums.push(_num);
}
function getCount() public view returns (uint){
return nums.length;
}
function getNumAtIndex(uint _index) public view returns (uint){
return nums[_index];
}
function getNums() public view returns (uint[] memory){
return nums;
}
}