DEV Community

Cover image for Solidity Arrays Part 2
Shlok Kumar
Shlok Kumar

Posted on

Solidity Arrays Part 2

Arrays in Solidity have built-in methods such as push, length, pop, shift, and unshift for adding, removing, and retrieving values in the array.

Array Members:

  • length − length returns the size of the array. Length can be used to change the size of the dynamic array by setting it.

  • push() − push allows you to append an element to a dynamic storage array at the end. It returns the new length of the array.

  • push(x):Dynamic storage arrays and bytes (not string) have a member function called push(x) that you can use to append a given element at the end of the array. The function returns nothing.

  • pop():Dynamic storage arrays and bytes (not string) have a member function called pop() that you can use to remove an element from the end of the array. This also implicitly calls delete on the removed element.

Important:

Increasing the length of a storage array by calling push() has constant gas costs because storage is zero-initialized, while decreasing the length by calling pop() has a cost that depends on the “size” of the element being removed. If that element is an array, it can be very costly, because it includes explicitly clearing the removed elements similar to calling delete on them.

The following code explains various array properties and methods:

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.10;

contract Array {
    // Several ways to initialize an array
    uint[] public arr;
    uint[] public arr2 = [1, 2, 3];
    // Fixed sized array, all elements initialize to 0
    uint[10] public myFixedSizeArr;

    function get(uint i) public returns (uint) {
        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 returns (uint[] memory) {
        return arr;
    }

    function push(uint 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 returns (uint) {
        return arr.length;
    }

    function remove(uint 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 {
        // create array in memory, only fixed size can be created
        uint[] memory a = new uint[](5);
    }
}
Enter fullscreen mode Exit fullscreen mode

Bytes and string as Arrays:

Arrays of the types bytes and string are special types of arrays. In many ways, the bytes type is identical to bytes1[], except it is compressed into a smaller amount of calldata and memory. Strings are equal to bytes, except they do not enable access to the length or index of the string.

Despite the fact that Solidity does not include any string manipulation functions, there are third-party string libraries available. Another useful function is keccak256(abi.encodePacked(s1)) == keccak256(abi.encodePacked(s2), which compares two strings based on their keccak256-hash. You can also concatenate two strings by using string.concat (s1, s2).

Use bytes rather than bytes1[] since it is less expensive. Using bytes1[] in memory adds 31 padding bytes between the elements, thus you should use bytes instead. It should be noted that the padding is absent in storage as a result of the tight packing (see bytes and string). When dealing with arbitrary-length raw byte data, bytes should be used and string should be used when dealing with arbitrary-length string (UTF-8) data. In cases when you are able to restrict the length to a specific number of bytes, always use one of the value types bytes1 to bytes32 because they are far more cost-effective.

Array Slicing:

When seeing an array slice, you are looking at a continuous section of the array. They are denoted by the notation x[start:end], where start and end are expressions that result in the type uint256 (or implicitly convertible to it). The initial element of the slice is represented by x[start], while the last piece is represented by x[end - 1.]

An exception is thrown if start is greater than end, or if end is greater than the length of the array, as the case may be. Neither the start nor the end are required; start defaults to 0 and end defaults to a value equal to the length of the array.

Array slices do not have any members in their arrays. In addition to supporting index access, they are implicitly convertible to arrays of their underlying type. The index access in the underlying array is not absolute, but rather relative to the beginning of the slice. Array slices do not have a type name, which means that they cannot be used as a type in a variable; instead, they can only be found in intermediate expressions.

bytes exampleBytes = '0xabcd'
exampleBytes[2:5]; # 'abc' 
exampleBytes[:5]; # '0xabc' 
exampleBytes[2:]; # 'abcd' 
exampleBytes[:]; # '0xabcd'
Enter fullscreen mode Exit fullscreen mode

Solidity Arrays Part 1 - https://dev.to/shlok2740/solidity-arrays-4cph
For more content, follow me on - https://linktr.ee/shlokkumar2303

Top comments (0)