0

I created a simple For loop that should return an array of numbers. But it fails with errored: VM error: revert

I guess there is something fundamental I am missing here, so I hope you guys can help here.

    // SPDX-License-Identifier: GPL-3.0

pragma solidity >=0.7.0 <0.9.0;

contract ForLoop {


     function getOwnedTokens() public pure returns (uint[] memory) {

        uint[] memory listOfOwnedTokens;

        uint numberOfOwnedTokens = 4;

        for(uint tokenIndex = 0; tokenIndex < numberOfOwnedTokens; tokenIndex++)  {
            listOfOwnedTokens[tokenIndex] = tokenIndex;
         }

        return listOfOwnedTokens;
    }

}

1 Answer 1

1
    // SPDX-License-Identifier: GPL-3.0

    pragma solidity >=0.7.0 <0.9.0;

    contract ForLoop {


 function getOwnedTokens() public pure returns (uint[] memory) {
    uint numberOfOwnedTokens = 4;
    uint[] memory listOfOwnedTokens = new uint[](numberOfOwnedTokens);



    for(uint tokenIndex = 0; tokenIndex < numberOfOwnedTokens; tokenIndex++)  {
        listOfOwnedTokens[tokenIndex] = tokenIndex;
     }

    return listOfOwnedTokens;
}

}

Here, i fixed it for you. Its kinda hard to explain the answer. But "it is not allowed" to index unfixed sized array that are memory.

1
  • Thanks! I knew I was missing something fundamental.
    – Sky
    Commented Jul 28, 2022 at 8:04

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.