Search code examples
c++language-designdynamic-memory-allocationdelete-operator

Why does the compiler require `delete [] p` versus `delete p[]`?


In C++, if you want to dynamically allocate an array, you can do something like this:

int *p;
p = new int[i];  // i is some number

However, to delete the array, you do...

delete[] p;

Why isn't it delete p[]? Wouldn't that be more symmetrical with how it was originally created? What is the reason (if there is any) why the language was designed this way?


Solution

  • One reason could be to make these cases more distinct.

    int ** p;
    delete[] p
    delete p[1];
    

    If it were delete p[] then a one character error would have pretty nasty consquences.