Pointer arithmetic is the one place where C++ lets you add to a pointer, and it works in a way that surprises everybody the first time. Adding one to a pointer does not move it one byte. It moves it one whole element forward, and the compiler works out the number of bytes from the type.
The previous lesson in this module covered "What Is a Pointer and What Do * and & Mean?", and the next lesson in this module is about "When Is a Reference the Right Alias?".
Adding one moves by the element size
This is the whole rule.
#include <iostream>
int main() {
int ratings[4] = {4, 5, 3, 5};
int* current = ratings;
std::cout << "sizeof(int): " << sizeof(int) << '\n';
std::cout << "*current: " << *current << '\n';
++current;
std::cout << "after ++: " << *current << '\n';
current = current + 2;
std::cout << "after +2: " << *current << '\n';
std::cout << "distance: " << (&ratings[3] - &ratings[0]) << '\n';
return 0;
}The output shows the pointer stepping from element to element, and the difference of two pointers counting the elements between them.
sizeof(int): 4
*current: 4
after ++: 5
after +2: 5
distance: 3Indexing is pointer arithmetic
When you write ratings[1], the compiler generates exactly the same code as *(ratings + 1), which is why the two forms always agree.
#include <iostream>
int main() {
double durations[3] = {180.0, 240.0, 200.0};
std::cout << "indexing: " << durations[1] << '\n';
std::cout << "pointer: " << *(durations + 1) << '\n';
double* pointer = durations;
std::cout << "offset: " << pointer[2] << '\n';
std::cout << "same: " << (durations[2] == *(pointer + 2)) << '\n';
return 0;
}The output shows all four of the expressions agreeing.
indexing: 240
pointer: 240
offset: 200
same: 1The four pointer operators
There are four operators that work on pointers.
*preads or writes the object that p points at.p + nmoves p forward by n elements.p - nmoves p back by n elements.p - qgives the number of elements between two pointers that point into the same array.
And pointer arithmetic is deliberately narrow, so that the mistakes are caught at compile time. You can only add an integer to a pointer, and you can only subtract a pointer from another pointer when both of them point into the same array.
#include <iostream>
int main() {
int scores[5] = {10, 20, 30, 40, 50};
int* begin = scores;
int* end = scores + 5;
int total = 0;
for (int* cursor = begin; cursor != end; ++cursor) {
total += *cursor;
}
std::cout << "total: " << total << '\n';
std::cout << "elements: " << (end - begin) << '\n';
std::cout << "middle: " << *(begin + 2) << '\n';
return 0;
}Walking off the end is unsafe behaviour
Anything else is undefined behaviour, and the compiler is allowed to assume that it never happens.
#include <iostream>
int main() {
int ratings[3] = {4, 5, 3};
int* begin = ratings;
int* end = ratings + 3;
int sum = 0;
for (int* cursor = begin; cursor != end; ++cursor) {
sum += *cursor;
}
std::cout << "sum: " << sum << '\n';
// One past the end is allowed as a value, but not to be dereferenced.
std::cout << "distance to end: " << (end - begin) << '\n';
return 0;
}The output is the safe, well-defined part.
sum: 12
distance to end: 3And that gives you the begin-and-end pattern. The pointer that is one past the end of an array is a legal value that you can hold and compare. You just may not dereference it.
Pointers into the middle of an array
Pointer arithmetic makes it easy to work with a slice of an array, and that is how you pass part of a buffer to a function.
#include <iostream>
double average(const double* begin, const double* end) {
if (begin == end) {
return 0.0;
}
double sum = 0.0;
const double* cursor = begin;
while (cursor != end) {
sum += *cursor;
++cursor;
}
return sum / static_cast<double>(end - begin);
}
int main() {
double durations[5] = {180.0, 240.0, 200.0, 210.0, 195.0};
std::cout << "all five: " << average(durations, durations + 5) << '\n';
std::cout << "middle two: " << average(durations + 1, durations + 3) << '\n';
return 0;
}The output shows the two ranges giving different answers.
all five: 205
middle two: 220Pointer arithmetic in a linked structure
And here is a linked structure, where the elements are not next to each other in the memory.
#include <iostream>
#include <string>
struct Node {
std::string title;
Node* next;
};
int main() {
Node third = {"Third", nullptr};
Node second = {"Second", &third};
Node first = {"First", &second};
int count = 0;
for (Node* current = &first; current != nullptr; current = current->next) {
std::cout << current->title << '\n';
++count;
}
std::cout << "nodes: " << count << '\n';
return 0;
}The output walks the chain.
First
Second
Third
nodes: 3And this is worth noticing, because it shows exactly what pointer arithmetic means. The array arithmetic works because the memory is contiguous. The linked list works because each element holds the address of the next one, so no arithmetic is needed at all.
Quick reference
- Adding one to a pointer moves it by the size of one element, not by one byte.
a[i]is exactly the same as*(a + i).- Only pointers into the same array can be subtracted from each other.
- The pointer one past the end is legal to hold and to compare, and it is not legal to dereference.
- The begin-and-end pointer pair is the shape that the standard library uses for every range.
- Pointer arithmetic only works on contiguous storage, so it cannot be used on a linked list.
Try it yourself: write a program with an array of five durations and then walk it with a pointer instead of an index, printing each value. Next, work out the average with a begin-and-end pointer pair and compare it with the average that you get from the ordinary loop. Finally, write a small function that takes a pointer and a count and gives back the largest value, and call it with the middle three elements of the array.