I am trying to create an Array and add elements to it. Once I add the elements I try to find the length of the two arrays, store the length into a fixed size array of two elements and then return it to the length function.
Following is the code -
pragma solidity ^0.8.7;
contract Array {
uint[10] public fixedArr; // fixed size array
uint[] public dynamicArr; // dynamic size array
function addTofixedArray(uint i, uint element) public {
fixedArr[i] = element;
}
function addToDynamicArray(uint element) public {
// Append to array
// This will increase the array length by 1.
dynamicArr.push(element);
}
function length() public view returns(uint[] memory) {
//uint[] memory lengthArray = new uint[](2); This line works
uint[2] memory lengthArray; // This line does not work
lengthArray[0] = fixedArr.length;
lengthArray[1] = dynamicArr.length;
return lengthArray;
}
}
In the above code I want to understand why I have to create an object of array using new() to return the array from the function. In other words, why the line uint[2] memory lengthArray;
does not work.
Error -
Return Argument Type uint256[2] is not implicitly convertible to expected type (type of first return variable) uint256[] memory.