0

I want to create a fixed array(w*h), w*his the maximum size, and when the condition meet(checkOwner(_temp) == msg.sender), the data(_temp) will store into the _array.

My question is if only few conditions meet, _array.length will still return w*h.

How do I let _array return the actual length of the value?

function Test(uint256 w, uint256 h) external {
    uint256[] memory _array = new uint[](w*h);
    uint _count = 0;
    for(uint j = 0; j<h; j++){
        uint256 _temp = ..... // do the calculation 

        // Call checkOwner function to check the owner
        if(checkOwner(_temp) == msg.sender){
            _array[_count] = _temp;
            _count ++;
        }
    }

    if(_array.length == w*h){
        ....
    }
}

1 Answer 1

1

When you declare an array as uint256[] memory _array = new uint[](w*h);, its size if fixed to be w*h. When you add elements to an array, you are merely changing the value of the item at that index, and not the size of the array itself. In the code you had mentioned, _count is the number of items that's been updated. You can use that value for your usecases. Hope this clarifies your question.

1
  • Thanks, I just find this answer few minutes ago. Haha
    – leojail
    Jan 27 at 9:13

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.