0

So, I tried 3 simple codes on array

// SPDX-License-Identifier: MIT
pragma solidity 0.8.7;

contract test{
    uint[] public x;

    function testing() public {
        x[0] = 20;
    }
}

This throws an error but if i use x.push(20) instead of x[0] = 20 then it works OR.....

if I declare the array as

uint[3] public x; 

and then use x[0] = 20 inside the function

then it works .... OR..... if I write it as :

uint[] public x = [1,2,3];

and use x[0] = 20 inside the function

then also it works... I dont understand the mechanism behind it

1 Answer 1

1

That's because your array is of size zero when you declare it like

uint[] public x;

So zeroth index doesn't exist and it throws an error. When you define the array with an explicit length it doesn't give any errors because then zeroth index does exist. If you want to use a dynamic array try using:

x.push()

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.