Allocating arrays of objects

You can also create arrays of objects in dynamic memory using the new operator. You do this by providing the number of items you want created in a pair of square brackets. The following code allocates memory for two integers:

    int *p = new int[2];     p[0] = 1;     *(p + 1) = 2;     for (int i = 0; i < 2; ++i) cout << p[i] << endl;     delete [] p;

The operator returns a pointer to the type allocated, and you can use pointer arithmetic or array indexing to access the memory. You cannot initialize the memory in the new statement; you have to do that after creating the buffer. When you use new to create a buffer for more than one object, you must use the appropriate version of the delete operator: the [] is used to indicate ...

Get Beginning C++ Programming now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.