5.2. Using pointers¶
The simplest way to use a pointer is to get their value as with any other variable. This value will be an address, which can be stored in another pointer variable of the same type.
int n = 2;
int* p = &n; // points to n
int* q = p; // points to n also
Once a pointer has been dereferenced, it is treated exactly like any other variable of that type.
*p = *p + *q; // n = 4
Pointers support many of the same operations as other arithmetic types.
Operation |
Result |
---|---|
|
|
|
negation of above |
|
refers to the value pointed to by |
|
writes |
|
reads from the location pointed to by |
|
increment the pointer, making it point to the next
memory address after |
|
add the integral value |
|
decrement the pointer, making it point to the previous
memory address before |
|
subtract |
The *
operator binds very tightly, in other words,
is it has high precedence.
You can usually use *p
anywhere you could use the variable it points to
without worrying about parentheses.
However, a few operators,
such as the unary decrement and increment (--
and ++
) operators,
and the member of (.
) operator used to unpack structs and classes,
all have higher precedence.
These require parentheses if you want the *
to take precedence.
Unlike the fundamental types in C++, pointer types do not implicitly convert to other types. While we expect to be able to assign an int to a double, it is a compile error to assign an int pointer to a double pointer:
int i = 5;
double d = i; // OK. implicit widening conversion
int* pi = &i;
double* di = pi; // compile error
More to Explore
From the ISO C++ FAQ: Does “Const Fred* p” mean that *p can’t change?