Returning an Array from a function is giving error – Return Argument Type uint256[2] is not implicitly convertible to expected type

remixsoliditysolidity-0.8.x

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.

Best Answer

Fixed length arrays (e.g. uint[2] memory) and dynamic length arrays (e.g. uint[] memory) are stored in memory differently, as the dynamic length array has to also store the length.

From the docs:

The length of a dynamic array is stored at the first slot of the array and followed by the array elements.

Due to this difference it is not possible to convert them automatically. More info is available in the Solidity docs on the internals:

Edit: An alternative for your example would be the usage of a tuple as the return type:

function length() public view returns(uint fixedLength, uint dynamicLength) { 
  return (fixedArr.length, dynamicArr.length); 
}
Related Topic