-
-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy path14_Arrays.sol
52 lines (41 loc) · 1.61 KB
/
14_Arrays.sol
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
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
contract Arrays{
/* Fixed Size Arrays */
uint constant SIZE = 5;
uint[SIZE] public x = [1, 2, 3, 4, 5];
// index: 0 1 2 3 4
uint[SIZE] public y = [10, 20];
// index: [0 1] 2 3 4 -> these indexes are initialized with 0
/* Dynamic Size Arrays */
uint[] public d = [1,2];
/* Dynamic Memory Arrays */
uint[] arr = new uint[](SIZE);
function dynamicArraysInMemory() external pure returns(uint[] memory){
uint[] memory abc = new uint[](SIZE);
for(uint i=0;i<abc.length;i++){
abc[0]=10000; // Initializing the first element
}
// abc.pop(); // This will cause an error
// 👆 Member "pop" is not available in uint256[] memory outside of storage.
return abc;
}
function arrayOperations() external {
// Adding elements to the array
d.push(); // This will push an empty element (here: uint 0)
// 👆 Output: [1,2,0]
d.push(100); // Overriding the default value to be pushed
// 👆 Output: [1,2,0,100]
// Delete elements from array
delete d[0]; // This will set the value of the first element to false value (0)
// 👆 Output: [2,0,100]
// Remove last element from array
d.pop(); // Implicitly calls the delete on removed element
// 👆 Output: [2,0]
/* Note:
- Increasing the length of a storage array by calling push() has constant gas costs because storage is zero-initialised.
- While decreasing the length gas cost depends upon the size.
- if it's an array getting deleted, Gas Cost will be high.
*/
}
}