0

So let's say that I have struct A and an array A[] of struct A's I then fill 3 first indexes of A[] with some A's. I then delete second index of A[] and and want to test if it has been deleted.

In other words:

A memory a = A({index: 1});
A memory a = A({index: 1});
A memory a = A({index: 1});
A[] arr;
arr.push(a);
arr.push(b);
arr.push(c);
delete arr[1];
//how do I check if arr[1] is deleted? looking for something like: if(arr[1] == null)
0
3

Check for a zeroish value. It could be null, 0, a string or bytes with .length==0, a bytes32==bytes32(0), etc.

In the case of a struct, check a member. The following example checks for 0 and interprets this to mean that the element was deleted. If 0 itself has meaning in your application then you can't interpret its presence as indicating nothing important is there. In this case, you may think of something else that must not (cannot) be 0 or if necessary, create a bool exists (set to true) explicitly for this purpose.

pragma solidity 0.4.25;

contract DeleteArrayElement {

    address[] public entities;

    constructor() public {
        entities.push(1); // [0]
        entities.push(2); // [1]
        entities.push(3); // [2]
        delete entities[1];
    }

    function isEmpty(uint row) public view returns(bool isIndeed) {
        return entities[row] == address(0);
    }

}

Hope it helps.

2
  • But what do I check for if it's an array of structs? Is a post-deletion empty spot a null?
    – lemme
    Oct 9 '18 at 17:46
  • All the struct members in the deleted array element will be 0. Try return a.index==0. Oct 9 '18 at 18:07
2

When an element or an array in storage is deleted the content is reset to zero bytes.

For example if you have

uint[3] ids;

function foo() public {
    ids[0] = 1;
    ids[1] = 0;
    ids[2] = 3;
    delete ids[0];
}

The content of ids[0] will be 0 after delete, but you cannot distinguish that value from ids[1] that is 0 from the beginning.

If you want to track deleted elements a common trick is to add a valid bool to the struct. When initialized is set to true, on deletion it will be reset to false.

If you do not have an struct but an array of uint for example, is common to use 0 as an invalid value, if you need to 0 to be valid instead of storing value you store value+1. When reading you check 0 means deleted, if you have m stored then you real value is m-1.

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.