1

I am trying to assign values to an Array, but it is giving me an error

from solidity: TypeError: Type uint8[5] memory is not implicitly convertible to expected type uint256[] memory. --> Web3/Array.sol:31:15: | 31 | val = [1,2,3,4,5];

function example() public{
    uint[] memory val = new uint[](5);
    val = [1,2,3,4,5];
}

1 Answer 1

2

What you were trying to do was assign a fixed size memory array [1,2,3,4,5] to a dynamically-sized memory array val. This is not allowed. If you want to initialize dynamically-sized arrays, you have to assign the individual elements:

 function example() public{
    uint[] memory val = new uint[](5);
    val[0] = 1;
    val[1] = 2;
    val[2] = 3;
    val[3] = 4;
    val[4] = 5;
}

See: https://docs.soliditylang.org/en/v0.8.12/types.html#allocating-memory-arrays

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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