| 1 |
// SPDX-License-Identifier: MIT |
| 2 |
pragma solidity ^0.8.17; |
| 3 |
|
| 4 |
contract Array { |
| 5 |
// Several ways to initialize an array |
| 6 |
uint[] public arr; |
| 7 |
uint[] public arr2 = [1, 2, 3]; |
| 8 |
// Fixed sized array, all elements initialize to 0 |
| 9 |
uint[10] public myFixedSizeArr; |
| 10 |
|
| 11 |
function get(uint i) public view returns (uint) { |
| 12 |
return arr[i]; |
| 13 |
} |
| 14 |
|
| 15 |
// Solidity can return the entire array. |
| 16 |
// But this function should be avoided for |
| 17 |
// arrays that can grow indefinitely in length. |
| 18 |
function getArr() public view returns (uint[] memory) { |
| 19 |
return arr; |
| 20 |
} |
| 21 |
|
| 22 |
function push(uint i) public { |
| 23 |
// Append to array |
| 24 |
// This will increase the array length by 1. |
| 25 |
arr.push(i); |
| 26 |
} |
| 27 |
|
| 28 |
function pop() public { |
| 29 |
// Remove last element from array |
| 30 |
// This will decrease the array length by 1 |
| 31 |
arr.pop(); |
| 32 |
} |
| 33 |
|
| 34 |
function getLength() public view returns (uint) { |
| 35 |
return arr.length; |
| 36 |
} |
| 37 |
|
| 38 |
function remove(uint index) public { |
| 39 |
// Delete does not change the array length. |
| 40 |
// It resets the value at index to it's default value, |
| 41 |
// in this case 0 |
| 42 |
delete arr[index]; |
| 43 |
} |
| 44 |
|
| 45 |
function examples() external { |
| 46 |
// create array in memory, only fixed size can be created |
| 47 |
uint[] memory a = new uint[](5); |
| 48 |
} |
| 49 |
} |
| 50 |
|
| 51 |
// From https://solidity-by-example.org/array/ |
| 52 |
|