4

Is it possible to do something like this:

int *iarray = new int[10];
.....
//do something with it
.....

and then in order to easily remove first element do this:

delete iarray;
iarray++;

it seems that delete (without [] ) still deletes whole array. If it's possible it would be really tricky and clever way to remove first element. The idea is not mine, I saw it somewhere, but it's doesn't work with me. Am I doing something wrong?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Marko
  • 1,267
  • 1
  • 16
  • 25
  • I asked this when I just started learning C++. It seems stupid now. Delete can't delete elements, only whole array. To remove elements from beginning, you should use different data structures depending on your use case. – Marko Apr 04 '19 at 13:55

3 Answers3

5

Use a deque to remove an element from the front — that's what this structure is invented for.

Alex Reynolds
  • 95,983
  • 54
  • 240
  • 345
2

It looks like you're writing C++, in which case the delete trick is madness and terrible and not going to work. You could certainly just get a pointer to the second element if that's what you really need by doing pointer math, but to actually remove the first item you're going to have to move everything back by one.

Ryan Cavanaugh
  • 209,514
  • 56
  • 272
  • 235
1

That won't work as you expect.

Check out this answer here:

How does delete[] know it's an array?

It pretty much answers your question.

Community
  • 1
  • 1
Jimadilo
  • 497
  • 3
  • 10
  • Thank you I understand now. It seems that in Linux, size of array is not kept four bytes before array it self (when using new[] ). I'll search for answer to that question, but If you know some link I would be very thankful if you post it. – Marko Dec 03 '12 at 22:35