Remove an element in array but the struct is still inside

by monkeyUser   Last Updated November 08, 2018 19:28 PM - source

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

owner: 0x0000000000000000000000000000000000000000

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


But before I have to resolve this issue

Tags : solidity arrays

Answers 1

There are a few issues with this approach. If you delete the element at index 0 and subtract 1 from the length, then the next time you try to insert an element, it'll overwrite the last element in the array. That's because delete prodotti[0] doesn't move the rest of the array to the left, it leaves the element in index 1 at index 1.

The reason you still get a struct from index 0 after deleting is because that's just how Solidity works. When you delete something from an array or mapping in Solidity, all you're really doing is zeroing out its values. That's why the struct it returns is all zeros.

IMO the best way to do this is leave it as you're doing it. Delete the element, but leave the length alone. Length is a misnomer really, it should be called tail or last because it's mostly used for knowing where the next element in the array will be.

November 08, 2018 19:04 PM

Related Questions

How to copy/assign an array via for loop

Updated July 02, 2017 23:28 PM

How to delete element of array, without index?

Updated August 09, 2017 17:28 PM

Is there a maximum array size in Solidity?

Updated August 10, 2017 08:28 AM

Delete an element from 2D array Solidity

Updated January 16, 2018 18:28 PM