0

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.

1 Answer 1

0

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); 
}
4
  • Does it mean that I can't pass fixed length array from a function?
    – user90145
    Dec 30, 2021 at 10:56
  • you can if you define the return type as uint[2] memory, but then only fixed length array with a length of 2 will be accepted.
    – Richard
    Dec 30, 2021 at 11:00
  • For your example you could also use a tuple as a return type (added it to the original answer)
    – Richard
    Dec 30, 2021 at 11:01
  • return type as uint[2] memory solved the problem. I am pretty sure, I tried it while troubleshooting but for some reason it did not work that time. Thanks for the help.
    – user90145
    Dec 30, 2021 at 11:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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