Skip to main content

Section 18.3 Types of Pointers

Every pointer has a type. A pointer might be a “pointer to an int” (int*), a “pointer to a double” (double*), or a “pointer to a Circle” (Circle*). This information is essential because it tells the compiler how to interpret the data that the pointer points to. For example, given double* p, the compiler knows that if we try to use the memory p points at, it only makes sense to use it as a double.
This sample creates three different pointers, p, p2, and p3, each of a different type:
Listing 18.3.1.
Trying to store the wrong kind of address into a pointer is a compile time error:
Listing 18.3.2.
It is also an error to try to store a value other than a memory address into a pointer. Given int x = 10;, we can’t ask a pointer to store x - that names the value 10, not the memory address of x.
Listing 18.3.3.

Note 18.3.1.

It is possible to declare a pointer with no specific type as a void*. However, because that address has no defined type, the compiler won’t let us do much with that address. It does not know if the address points at data that should be treated as a double, an int, or a Circle.

Note 18.3.2.

Much like references, pointers can be declared “const”. But, there is an added wrinkly: you can declare either the data it points to as “const”, meaning you can’t change the data through the pointer, or the pointer itself as “const”, meaning the memory address the pointer has can’t be changed. You can even declare both the pointer and the data it points at as being const. Here are some examples:
  • int* const p = &x p is a constant pointer to an int, meaning the pointer itself cannot be changed to point to another int, but the int it points to (x) can be modified.
  • const int* p = &x p is a pointer to a constant int, meaning the int it points to cannot be modified through the pointer, but the pointer itself can be changed to point to another int.
  • const int* const p = &x p is a constant pointer to a constant int, meaning neither the pointer nor the int it points to can be modified.
Remember that it helps to read these declarations from right to left to understand what is constant.
We will not be making use of const pointers in this book.

Checkpoint 18.3.1.

Which statements below are correct?
  • Any pointer variable can be assigned any variable’s address.
  • Pointers can only be assigned the address of variables of the matching type.
  • All pointers store memory addresses.
  • All pointers just store memory addresses.
  • The compiler uses a pointer’s type to determine what can be done with what it points at.
  • That is why pointers have types.
  • You can assign an int value like 42 to a int*.
  • Pointers can only be assigned memory addresses, not the values of the type they are supposed to point at.
You have attempted of activities on this page.