The Free Store and Built-In Types

The new and delete operators can be used not only with classes that you've defined, but also with built-in types like integers and characters. For example:

int *ip;

ip = new int; // Allocate an integer

// use ip

delete ip;

You can also allocate arrays whose size is determined at run time:

int length;

char *cp;

// Assign value to length, depending on user input

cp = new char[length]; // Allocate an array of chars

// Use cp

delete [] cp;

Notice the syntax for declaring an array: you place the array size within brackets after the name of the type. Also note the syntax for deleting an array: you place an empty pair of brackets before the name of the pointer. The compiler ignores any number you place inside the brackets.

You can even allocate multidimensional arrays with new, as long as all of the array dimensions except the first are constants. For example:

int (*matrix)[10];

int size;

// Assign value to size, depending on user input

matrix = new int[size][10]; // Allocate a 2-D array

// Use matrix

delete [] matrix;

Dynamic allocation of arrays of objects, as opposed to arrays of built-in types, is discussed in Chapter 6.