'Function needs to return array length in solidity, but error occurs
I have a Practice contract in solidity. I was trying to get the length of an array using arrLength function.But, I am getting error like 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.
Here, I am trying to any transaction, But getting error like the function should be payable.
// SPDX-License-Identifier: MIT
pragma solidity >=0.5.0 <0.9.0;
contract Practice {
function arrLength(uint num) public pure returns(uint){
uint[] memory arr = new uint[](num);
for(uint i = 0; i<=num; i++){
arr[i] = 10;
}
return arr.length;
}
}
But I am getting error:
creation of Practice pending...
[vm]from: 0x5B3...eddC4to: Practice.(constructor)value: 0 weidata: 0x608...70033logs: 0hash: 0x029...1dcf6
call to Practice.arrLength
call to Practice.arrLength errored: VM error: revert.
revert
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.
Solution 1:[1]
You Should Try this Code :
// SPDX-License-Identifier: MIT
pragma solidity >=0.5.0 <0.9.0;
contract Practice {
function arrLength(uint num) public pure returns(uint){
uint[] memory arr = new uint[](num);
for(uint i = 0; i < num; i++){
arr[i] = 10;
}
uint leng= arr.length;
return leng;
}
}
You have error in this line :
for(uint i = 0; i<=num; i++)
change it to for(uint i = 0; i<num; i++)
for example you enter 5 into the input of the function .
now your array size is 5 : arr[0] , arr[1],arr[2],arr[3],arr[4]
when you use this code : for(uint i = 0; i<=num; i++) , it try to add item into arr[5] but it not exsist .
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
