This module explores how C++'s use of pointers and memory allocation differs from C.
While pointers are used in much the same way in both languages, C++ introduces some interesting new features. In addition, C++ allows you to control the allocation and deallocation of a system-provided memory pool. This feature is particularly important for using dynamic data structures such as lists and trees.
C provides a remarkably useful type of variable called a pointer
. A pointer is a variable that stores an address and its value is the address of another location in memory that can contain a value. You already used an address when you used the
- scanf() and
functions. A pointer variable
with the name pNumber is defined by the second of the following two statements:
int Number = 25;
int *pNumber = &Number;
You declare a variable, Number, with the value 25, and a pointer, pNumber, which contains the address of Number. You can now use the variable pNumber in the expression *pNumber to obtain the value contained in Number.
The * is the dereference operator,
and its effect is to access the data stored at the address specified by a pointer.