Is there a way that can change {3, 5, 3, 6}
to {3, 5, 6}
with a function? I checked all the arduino forums but they don't give the answer i need (just delete 1 item from an array with a function like delete(myArray, 2)
).
2 Answers
There is no such concept in C. Arrays are a fixed size and that size can never be changed. You can't "delete" an entry. You can replace one with something else, and you can introduce the concept of a variable that says how many entries the array has, but you can't delete one.
So you could:
- Keep a count of how many entries are in the array
- Shuffle down all the entries one space so the unused one is at the end
- Decrement the count of entries
So in your example {3, 5, 3, 6}
becomes {3, 5, 6, 6}
and your "count" holds 3
to say the first three entries are valid and to ignore the last.
Alternatively you can introduce the concept of "end of array". C strings do this with the NULL character (0). Anything before that character is valid, and anything from that character onwards is ignored. So say you nominated the value -1 to be "end of array" you could have, after again shuffling down the values: {3, 5, 6, -1}
.
You could also have -1
(or whatever you chose) indicating an "invalid" entry, so your array would be {3, 5, -1, 6}
and you would ignore the -1
entry in your code.
-
Using an invalid value (vs. an end-of-array value) saves shuffling values to over-write the vacated space, but adds some overhead in that array indexing would no longer work as expected but would require walking the array and counting valid values until the i-th one. Some applications may benefit (those that just store data but don't index to it, or not often, anyway), vs. those that do a lot of indexing but not much deleting.– JRobertCommented Jul 7, 2020 at 17:09
In C++, arrays are fixed-length data structures. There is no way you could remove an item. You could replace it with an invalid item, though.
-
-
Dynamic objects are not a good idea on a memory-starved device like an Arduino. Come up with a "this space intentionally left blank" value and store that into a location to remove an item. (0 and -1 are common choices for an empty entry, as Majenko mentions in their answer.)– Duncan CCommented Jul 7, 2020 at 15:49