Datasheet
Now that the memory has been allocated, you can work with myVariableSizedArray as though it
were a regular stack-based array:
myVariableSizedArray[3] = 2;
When your code is done with the array, it should remove it from the heap so that other variables can use
the memory. In C++, you use the
delete command to do this.
delete[] myVariableSizedArray;
The brackets after delete indicate that you are deleting an array.
Working with Pointers
There are other reasons to use heap memory besides dynamically allocating arrays. You can put any
variable in the heap by using a similar syntax:
int* myIntegerPointer = new int;
In this case, the pointer points to just a single integer value. To access this value, you need to dereference
the pointer. Think of dereferencing as following the pointer’s arrow to the actual value in the heap. To
set the value of the newly allocated heap integer, you would use code like the following:
*myIntegerPointer = 8;
Notice that this is not the same as setting myIntegerPointer to the value 8. You are not changing the
pointer, you are changing the memory that it points to. If you were to reassign the pointer value, it
would point to the memory address 8, which is probably random garbage that will eventually make
your program crash.
Pointers don’t always point to heap memory. You can declare a pointer that points to a variable on the
stack, even another pointer. To get a pointer to a variable, you use the
& “address of” operator:
int i = 8;
int* myIntegerPointer = &i; // Points to the variable with the value 8
C++ has a special syntax for dealing with pointers to structures. Technically, if you have a pointer to a
structure, you can access its fields by first dereferencing it with
*, then using the normal . syntax, as in
the code that follows, which assumes the existence of a function called
getEmployee().
EmployeeT* anEmployee = getEmployee();
cout << (*anEmployee).salary << endl;
The C++ commands new and delete are similar to malloc() and free() from C.
The syntax of
new and delete is simpler because you don’t need to know how many
bytes of memory are required.
20
Chapter 1
04_574841 ch01.qxd 12/15/04 3:39 PM Page 20










