Home > Software design >  Equal opeartor not working with Array in Solidty
Equal opeartor not working with Array in Solidty

Time:11-22

I wrote a simple solidity programme:-

//SPDX-License-Identifier: MIT
pragma solidity 0.8.16 ;
 contract arr
 {     uint256[] public n ;
       uint256 x = 0 ;

  function pl(uint256 a ) public
    {
      n[x] = a ;
      x   ;
     }
 }

It is showing below error

Error showing image while calling function

It reads that

The transaction has been reverted to the initial state. Note: The called function should be payable if you send value and the value you send should be less than your current balance. Debug the transaction to get more information.

I am new to solidity. Can anyone please explain it to me that why = opearator is not working with arrays. I read that Solidity is similar to Javascript & in Jsp it is working fine ?

CodePudding user response:

You're trying to assign into a non-existent index.

Use .push() to add new item to the array.

function pl(uint256 a) public {
    n.push(a);
}

CodePudding user response:

In the Dynamic array in Solidity you can't do what you are trying to do. Here is the fixed array code :

//SPDX-License-Identifier: MIT
pragma solidity 0.8.16 ;
 contract arr
 {     uint256[4] public n ;
       uint256 x = 0 ;

  function pl(uint256 a ) public
    {
      n[x] = a ;
      x   ;
     }
 }

This code works for me as I am declaring the size of the array. If you really wanna do it dynamically you have to first push a value in the dynamic array, then you can change a value with "Equal" sign. Here is the dynamic array code:

//SPDX-License-Identifier: MIT
pragma solidity 0.8.16 ;
 contract arr
 {     uint256[] public n ;
       uint256 x = 0 ;

  function pl(uint256 a ) public
    {
      n.push();
      n[x] = a ;
      x   ;
     }
 }
  • Related