With I use delete []p, the corruption of heap will occur.
Rectangle *p[3];
for (int i = 0; i<3; i++)
  p[i] = new Rectangle();
p[0]->set(3, 4); 
p[1]->set(10, 8); 
p[2]->set(5, 6); 
for(int i=0; i < 3; i++) 
    cout << "Area is " << p[i]->area() << endl; 
delete []p; 
After I change delete [] to
for (int i = 0; i<3; i++)
    delete p[i]; 
It works but why I cannot use delete []p? Is delete []p only deletes p[0] and what [] means in delete []p?
delete [] is only to be used after an allocation with new [], and delete only after new.
This is how C++ works. If you want to simply allocate an array of 3 Rectangle's, use this:
Rectangle *p = new Rectangle[3];
...
delete [] p;
                        delete [] x is for dynamically allocated arrays, not for arrays of pointers to dynamically allocated elements, which is what you have:
Rectangle* pA = new Rectalgle[3]; // dynamically allocated array
....
delete [] pA;  // OK
Rectangle* p[3]; // array of pointers. 
// Each pointer must be dealt with individually.
delete p[0]; // Might be OK, if p[0] points to dynamically allocated Rectangle.
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With