If it is necessary or desired to use pointers anyway, the right way to allocate an array of things is with p = new Fred[n]. When the array is deallocated, the [] must appear just after the delete keyword, such as delete[] p;. Here is an example. class Fred { }; int main() { Fred* p = new Fred[100]; <-- 1 delete[] p; <-- 2 }
The purpose of the syntactic difference between delete p and delete[] p is to distinguish deleting a thing from deleting an array of things. This is because there is no syntactic difference between the type "pointer to a thing" (Fred*) and the type "pointer to the first element of an array of things" (Fred*). This is a feature that C++ inherited from C. After all this, recall that the real solution is to not use pointers at all but instead to use a good container class library. For example, when an array of things is needed, use a container class that implements an array of things, such as the standard template vector (see FAQ 28.13). |