Programming C++   «Prev  Next»
Lesson 1

Introduction to Pointers and Memory Allocation in C++

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.

Idea of a Pointer

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
  1. scanf() and
  2. scanf_s()
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.
This module discusses:
  1. How to create const pointer arguments to functions
  2. How to create aliases for variables using reference declarations
  3. How C++ implements call-by-reference using reference declaration
  4. How to use a generic pointer type
  5. How to use new and delete to manipulate free store memory
  6. How to create dynamically allocated multidimensional arrays
At the end of the module, you will be given the opportunity to take a quiz covering these topics.