C++ Notes: Pointers

Pointers in C/C++

Pointers are variables that contain memory addresses (see Addresses, Pointers, and References). They are an essential data type in C and C++, and are used for the following:

Declaring a pointer

Pointers are declared to point to a particular datatype. A "*" is written after the type to indicate that this is a pointer to that type. For example, a pointer to an int would be declared like this.
int* ip;  // declares ip to be a pointer to an int.
You will also see variations in the spacing such as
int *ip;
int * ip;

NULL

NULL is the pointer to nothing, and should be used as the initial value for pointers because using NULL will cause an error in most systems.

Pointer operators: * (dereference), & (address of), and arithmetic

Two operators are used when dealing with memory addresses:

Example

char* cp;     // declare pointer to char
char  c, d;   // declare char variables

cp  = &c;     // puts address of c into cp
c   = 'x';    // assigns 'x' to c
*cp = 'x';    // also assigns 'x' to c
d   = *cp;    // copies c's value to d
cp  = &d;     // puts address of d into cp
*cp = c;      // puts value of c into d