1

I have this array of struct

struct Prodotto {
    string titolo;
    address owner_address;
}

Prodotto[] public prodotti;

And I create two products like this:

titolo: titolo stravolto
owner: 0x144c9617C69B52547f7c2c526352E137488FAF0c

titolo: titolo secondo prodotto
owner: 0xa53709839ab6Da3ad9c1518Ed39a4a0fFCbA3684

I want to delete the element with index 0

in my contract I have this function

function deleteProdotto(uint _id_prodotto) external payable onlyOwnerOf(_id_prodotto) {
  delete prodotti[0];    
}

If I retrive element to index 0, I have a product like this

titolo:
owner: 0x0000000000000000000000000000000000000000

How can I delete that index? I know that after that I have to do

prodotti.length--

But before I have to resolve this issue

monkeyUser
  • 4,301
  • 7
  • 46
  • 95
  • Possible duplicate of [Is there a pop functionality for solidity arrays?](https://stackoverflow.com/questions/49051856/is-there-a-pop-functionality-for-solidity-arrays) – Adam Kipnis Nov 09 '18 at 01:39

2 Answers2

0

You will have to move every element after that so that you don't leave a "gap". There is not a way to delete and rearrange the elements unless you do it yourself.

nikos fotiadis
  • 1,040
  • 2
  • 8
  • 16
0

Try this code

contract test {
    struct Prodotto {
        string titolo;
        address owner_address;
    }
    Prodotto[] public prodotti;

    constructor() public {
        for (uint i = 0; i < 5; i++) {
            prodotti.push(Prodotto({
                titolo: 'one more',
                owner_address: address(i)
            }));
        }
    }

    function remove(uint index) public {
        for (uint i = index; i < prodotti.length-1; i++) {
            prodotti[i] = prodotti[i+1];
        }
        delete prodotti[prodotti.length-1];
        prodotti.length--;
    }

    function check() public view returns(uint256) { return prodotti.length; }
}
Yegor
  • 3,652
  • 4
  • 22
  • 44
  • This seems highly inefficient. In some cases, it could be necessary, but if you do not care about the order, you can just move the last one only. – Marco Altieri Jul 18 '21 at 18:32