20B. Operations on Pointers

This page describes a few fundamental operations for creating and working with pointers.

&x

If x is a variable then &x is the memory address where x is stored. So

  int v;
  int* p = &v;
makes variable p hold the address of variable v. Observe that, for any type T:

If v has type T, then &v has type T *.

For example, if x has type int then &x has type int*.


*p

If p is a pointer then *p is the variable to which p points. For example,
  int  v = 1;
  int* p = &v;
  *p = 2;
ends with v = 2, since *p is the same a v, as shown in the following diagram.

For any type T:

If p has type T * then *p has type T.

For example, pointer p declared above has type int*. So *p has type int.


q = p;

If you set pointer variable q equal to pointer variable p, then you are making q hold the same memory address as p. So q and p point to the same place, as in the following diagram.

It does not make q point to p.


*q = *p;

Remember that *p is the variable to which p points. Assignment *q = *p sets the variable to which q points equal to the variable to which p points. That is not at all the same as assignment q = p. For example, after
  int  x = 1, y = 2;
  int* p = &x
  int* q = &y;
  *q = *p;
variable y holds 1, since *p is the same as x and *q is the same as y, as illustrated:



The relationship between & and *

Operators & and * are opposites of one another.

In fact, *&x is always the same as x. Draw a pointer diagram and work that fact out from your diagram.


Helpful mnemonics

Notice that you write * after a type but before a variable. Here is a way to remember that. In declaration

  int * p;
the star comes between type int and variable p. That is, star comes after the type and before the variable. Recall that, for any type T, declaration
  T x;
declares variable x to have type T. So declaration
  int* p;
declares variable p to have type int*. Now, let's move the *:
  int *p;
That appears to be saying that *p has type int. And it does. C++ is free-form, and whether you write a space before or after * makes no difference in meaning.

Saying that p has type T* is equivalent saying that *p has type T.

Exercises

  1. Suppose that w is a variable of type long. Write a statement that creates a variable q of type long* and makes q hold the address of variable w. Answer

  2. Are statements

      int r = 0;
      long* p = &r;
    
    allowed? Answer

  3. Are statements

      long r = 0;
      long* p = r;
    
    allowed? Answer

  4. Suppose that p is a pointer of type int*. Write a statement that stores 25 into the variable to which p points. Answer

  5. Suppose that variable p has type Widget*. What is the type of expression *p? Answer

  6. Suppose that variable w has type Widget. What is the type of expression &w? Answer