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.
1#include <iostream>
2int main() {
3 int n = 2;
4 int* p = &n; // points to n
5 int* q = p; // points to n also
6 *p = *p + *q; // n = 4
7 std::cout << "n = " << n << '\n';
8
9 int* p2n = &n; // another pointer to n
10 (*p)++; // increments n
11 std::cout << "n = " << n << '\n';
12 std::cout << "* p = " << * p << '\n';
13 *p++; // increments p
14 // p now points to next address in memory
15 // Almost always an error
16 std::cout << "* p = " << * p << '\n';
17
18 return 0;
19}
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?