# C++ Notes: Pointers

## Memory addresses

Every byte in memory has an integer memory address. Addresses start at zero and go to the maximum amount of memory that the computer has (eg, 64 MB).

## Pointers in C/C++

C and C++, but not all programming languages, have variables that hold the address of a memory location, not a simple data value. These are called pointers. Pointers are an extremely powerful programming feature, long regarded as essential to any full-strength programming language. The power of pointers also comes at a price, and safe use of pointers turns out to be rather difficult in large programs and the source of many bugs.

## Main uses: arrays and dynamic memory allocation

There are two places that you will encounter extensive use of pointers: working with arrays, especially char arrays, and in dynamic memory allocation of data structures.

## 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.

## 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) and & (address of)

Two operators are used when dealing with memory addresses:

- Unary & gives the address of (pointer to) something.
- Unary * takes the contents of a pointer (dereferences a pointer).

You may also do some addition and subtraction operations.

## 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

## References and Pointers

C++ introduced the concept of references. References are pointers that you can't manipulate with addition and subtraction. Removing this capability makes references much safer to use than pointers.