-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathArray.sol
More file actions
64 lines (53 loc) · 1.75 KB
/
Array.sol
File metadata and controls
64 lines (53 loc) · 1.75 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.26;
contract Array {
// Several ways to initialize an array
uint256[] public arr;
uint256[] public arr2 = [1, 2, 3];
// Fixed sized array, all elements initialize to 0
uint256[10] public myFixedSizeArr;
function get(uint256 i) public view returns (uint256) {
return arr[i];
}
// Solidity can return the entire array.
// But this function should be avoided for
// arrays that can grow indefinitely in length.
function getArr() public view returns (uint256[] memory) {
return arr;
}
function push(uint256 i) public {
// Append to array
// This will increase the array length by 1.
arr.push(i);
}
function pop() public {
// Remove last element from array
// This will decrease the array length by 1
arr.pop();
}
function getLength() public view returns (uint256) {
return arr.length;
}
function remove(uint256 index) public {
// Delete does not change the array length.
// It resets the value at index to it's default value,
// in this case 0
delete arr[index];
}
function examples() external pure {
// create array in memory, only fixed size can be created
uint256[] memory a = new uint256[](5);
// create a nested array in memory
// b = [[1, 2, 3], [4, 5, 6]]
uint256[][] memory b = new uint256[][](2);
for (uint256 i = 0; i < b.length; i++) {
b[i] = new uint256[](3);
}
b[0][0] = 1;
b[0][1] = 2;
b[0][2] = 3;
b[1][0] = 4;
b[1][1] = 5;
b[1][2] = 6;
}
}