Datasheet

Dynamically Allocated Arrays
Due to the way that the stack works, the compiler must be able to determine at compile time how big
each stack frame will be. Since the stack frame size is predetermined, you cannot declare an array with a
variable size. The following code will not compile because the
arraySize is a variable, not a constant.
int arraySize = 8;
int myVariableSizedArray[arraySize]; // This won’t compile!
Because the entire array must go on the stack, the compiler needs to know exactly what size it will be so
variables aren’t allowed. However, it is possible to specify the size of an array at run time by using
dynamic memory and placing the array in the heap instead of the stack.
To allocate an array dynamically, you first need to declare a pointer:
int* myVariableSizedArray;
The * after the int type indicates that the variable you are declaring refers to some integer memory in
the heap. Think of the pointer as an arrow that points at the dynamically allocated heap memory. It does
not yet point to anything specific because you haven’t assigned it to anything; it is an uninitialized
variable.
To initialize the pointer to new heap memory, you use the
new command:
myVariableSizedArray = new int[arraySize];
This allocates memory for enough integers to satisfy the arraySize variable. Figure 1-3 shows what the
stack and the heap both look like after this code is executed. As you can see, the pointer variable still
resides on the stack, but the array that was dynamically created lives on the heap.
Figure 1-3
Stack
myVariableSizedArray
Heap
myVariableSizedArray[0]
myVariableSizedArray[1]
myVariableSizedArray[2]
myVariableSizedArray[3]
myVariableSizedArray[4]
myVariableSizedArray[5]
myVariableSizedArray[6]
myVariableSizedArray[7]
Some C++ compilers actually do support the preceding declaration, but is not cur-
rently a part of the C++ specification. Most compilers offer a “strict” mode that will
turn off these nonstandard extensions to the language.
19
A Crash Course in C++
04_574841 ch01.qxd 12/15/04 3:39 PM Page 19