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.

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.