DEV Community 👩‍💻👨‍💻

Cover image for Day 10 - Arrays
Vedant Chainani
Vedant Chainani

Posted on • Updated on

Day 10 - Arrays

GitHub logo Envoy-VC / 30-Days-of-Solidity

30 Days of Solidity step-by-step guide to learn Smart Contract Development.

This is Day 10 of 30 in Solidity Series
Today I Learned About Arrays in Solidity.

Arrays are data structures that store the fixed collection of elements of the same data types in which each and every element has a specific location called index. Instead of creating numerous individual variables of the same type, we just declare one array of the required size and store the elements in the array and can be accessed using the index. In Solidity, an array can be of fixed size or dynamic size. Arrays have a continuous memory location, where the lowest index corresponds to the first element while the highest represents the last element.

Creating an Array

To declare an array in Solidity, the data type of the elements and the number of elements should be specified. The size of the array must be a positive integer and data type should be a valid Solidity type

Syntax -

<data type>[<size optional>] <name> = <initialization>
Enter fullscreen mode Exit fullscreen mode

Fixed-size Arrays

The size of the array should be predefined. The total number of elements should not exceed the size of the array. If the size of the array is not specified then the array of enough size is created which is enough to hold the initialization.

Example -

// SPDX-License-Identifier: MIT

pragma solidity ^0.8.7;

contract MyContract {
    // Declaring Array
    uint256[6] fixedArray;

    // Defining function to assign value to fixed Array

    function assignValueToFixedArray() public returns (uint256[6] memory) {
        fixedArray = [10, 20, 30, 40, 50, 60];
        return (fixedArray);
    }
}
Enter fullscreen mode Exit fullscreen mode

Output -

"0": "uint256[6]: 10,20,30,40,50,60"
Enter fullscreen mode Exit fullscreen mode

Dynamic Arrays

The size of the array is not predefined when it is declared. As the elements are added the size of array changes and at the runtime, the size of the array will be determined.

Example -

// SPDX-License-Identifier: MIT

pragma solidity ^0.8.7;

contract MyContract {
    // Declaring Array
    uint256[] dynamicArray;

    // Defining function to assign value to dynamic Array
    function assignValueToDynamicArray() public returns (uint256[] memory) {
        dynamicArray = [1, 5, 3, 7, 9, 1, 2, 6];
        return (dynamicArray);
    }
}
Enter fullscreen mode Exit fullscreen mode

Output -

"0": "uint256[]: 1,5,3,7,9,1,2,6"
Enter fullscreen mode Exit fullscreen mode

Top comments (0)

🌚 Life is too short to browse without dark mode