Deleting individual elements from an array

How would you use pointers to delete an individual element from an array? My homework problem requires me to drop the lowest value and we have not learned about vectors.
You can't. You have to either shift all the elements after it to the left by one and end up with an unused slot, or you need to make a new one with the size of the old one -1 and copy all the values except the one you're dropping into it, then delete the old array.
I find it amusing that you are required to use pointers but don't know how to use a vector, even though you obviously know what they are. Whats the deal with that?

LB answered your question though.
Last edited on
It is important to know how to use pointers. The std::vector class abstracts that all away for you, making it useless when learning how to work with pointers.

@frzatchary
Often, especially when working with pointers, it is useful to draw yourself a picture. (This is the best part, because I get to pull out the crayons and construction paper.)

┌─┬─┬─┬─┬─┬─┬─┬─┐
│D│e│s│s│e│r│t│ │
└─┴─┴─┴─┴─┴─┴─┴─┘
 ^     ^       ^
 head  |       tail
       to delete

Of course you have a pointer to the first item in your array (the head).
You should also have a pointer to the item to delete.
And it is useful to have a pointer to the one-past-the-last item (the tail).

In order to "delete" the item, you need to "shift" everything on the right of "to delete" leftward one cell, so that it looks like this:

┌─┬─┬─┬─┬─┬─┬─┬─┐
│D│e│s│e│r│t│t│ │
└─┴─┴─┴─┴─┴─┴─┴─┘
 ^     ^       ^
 head          tail

All that takes is a simple loop.

Now you need to update your 'tail' pointer. (Assuming, of course, that you actually keep it somewhere. If you just caculated it by adding the number of items in your array to the 'head' pointer, then this step is pointless.)

┌─┬─┬─┬─┬─┬─┬─┬─┐  
│D│e│s│e│r│t│t│ │
└─┴─┴─┴─┴─┴─┴─┴─┘
 ^           ^
 head        tail

Hope this helps.
Last edited on
but, how to delete the last item so the last item is not "echoed" within the array? i mean the logic flow... (cause this "tutorial" seems like incomplete... :D)
Last edited on
Duoas example has correctly updated the tail pointer. The convention in C++ (esp. STL) is for the tail pointer (or iterator, in the STL case) to refer to the element one past the end of the list. Here, the final 't' would not be displayed (see where the pointer was at the start of the sequence).

If you want to "scrub" your data, you could zero the elem (set it to '\0') at the same time you update the pointer. But this won't effect the output.
Topic archived. No new replies allowed.