8

The code gives the following error in solidity v0.6 compiler but works fine with compiler v0.5:

TypeError: Member "length" is read-only and cannot be used to resize arrays. nodes.length = 0;

pragma solidity >=0.4.22 <0.7.0;

contract TestNode { 
    uint[] nodes;

    function createNode(uint data) public {
        nodes.length = 0; // This line gives the ERROR
        nodes.push(data);
    }

    function pushNode(uint data) public {
        nodes.push(data);
    }

    function getNode() public view returns(uint[] memory) {
        return nodes;
    }
}

How to convert the code that works with solidity v0.6?

2 Answers 2

9

I think that'll do it.

pragma solidity 0.6.1;

contract TestNode { 
    uint[] nodes;

    function createNode(uint data) public {
        delete nodes; // This should reset the length to zero
        nodes.push(data);
    }

    function pushNode(uint data) public {
        nodes.push(data);
    }

    function getNode() public view returns(uint[] memory) {
        return nodes;
    }
}

If you only wanted to remove the last element, then you would array.pop().

Hope it helps.

7

Since v0.6.0 you can not resize array.length. Member-access to length of arrays is now always read-only, even for storage arrays. It is no longer possible to resize storage arrays by assigning a new value to their length.

Use push(), push(value) or pop() instead, or assign a full array, which will of course overwrite the existing content. The reason behind this is to prevent storage collisions of gigantic storage arrays.

Your Answer

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

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