Invalid implicit conversion from uint256[10] memory to uint256[] memory requested

Viewed 172

So apparently we can not use dynamic arrays while using memory data location. But the following code gives me error:

// SPDX-License-Identifier: GPL-3.0

pragma solidity >=0.7.0 <0.9.0;

contract A {
    uint256[] public numbers;
    
    constructor(uint256[] memory _numbers) {
        for(uint256 i=0; i<_numbers.length; i++) {
            numbers.push(_numbers[i]);
        }
    }

    function get() public view returns (uint256[] memory) {
        return numbers;
    }
}

contract Manager {
    function makeA() public returns(uint256) {
        uint256[10] memory numbers;
        // push is not supported for memory data location of array
        numbers[0] = 10;

        A a = new A(numbers); //Error: Invalid implicit conversion from uint256[10] memory to uint256[] memory requested

        return a.numbers(0);
    }
}

I solved it using this syntax of declaring static array:

uint256[] memory numbers = new uint256[](5);

Although it solved the issue but I am still confused behind the concept of why the later works? My assumption is that solidity differs the type between uint256[] and uint256[10]. Correct me if I am wrong, also an explanation of this behavior will be helpful.

1 Answers

The difference is as follows:

Firstly, a static array will have its memory slots allocated when defined.

Yet dynamic arrays will require a new allocation to be issued every time you push a new element into it.

This might not seem like a big thing in a normal OOP language, but Solidity requires gas per instruction, and that's where that difference can't be ignored.

Related