|
This page describes a few fundamental operations for creating and working with pointers.
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:
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:
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: ![]() |
Operators & and * are opposites of one another.
If x has type T, then &x has type T*. So
Prefix operator & adds a * to the type of a variable. |
If p has type T*, then *x has type T. So
Prefix operator * removes a * from the type of a variable. |
In fact, *&x is always the same as x. Draw a pointer diagram and work that fact out from your diagram.
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. |
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
int r = 0; long* p = &r;allowed? Answer
long r = 0; long* p = r;allowed? Answer
Suppose that p is a pointer of type int*. Write a statement that stores 25 into the variable to which p points. Answer
Suppose that variable p has type Widget*. What is the type of expression *p? Answer
Suppose that variable w has type Widget. What is the type of expression &w? Answer
|