1

Tell me what the 3rd line is doing please.

int main(){

int *p = new int[3];

*p++=0; // What's this line doing?

delete p;

return 0;   
}
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Arch1tect
  • 4,128
  • 10
  • 48
  • 69

3 Answers3

3

*p++=0; means this:

  1. Write sizeof(int) zero bytes to an address stored in p.
  2. Increment the value of p by sizeof(int).

In other words — you have incremented the pointer and what you then passing to delete is not the same as was returned by operator new[].

As @FredLarson has also mentioned, you have to use delete [] p; in order to delete an array.

Also, I'd recommend you read up on pointers, pointer arithmetics and pre-/post-increment. Pick a book from our Definitive C++ Book Guide and List.

Community
  • 1
  • 1
1

The first element in the array is set to 0 and p is advanced by one to point to the second element.

delete p; // this has undefined behaviour

Use delete [] p; instead.

Yang Zhang
  • 4,540
  • 4
  • 37
  • 34
0

You are setting p[0] to 0 and advancing the pointer to p[1]. What are you trying to do?

robert_difalco
  • 4,821
  • 4
  • 36
  • 58