A pointer in C++ is a variable that stores the address of another object. Two operators do all of the work. The ampersand takes the address of something, and the asterisk dereferences a pointer to reach the thing it points at. Once those two ideas are clear, pointers stop being mysterious and they become the tool for building linked structures such as a playlist.
This is the first lesson in the Pointers and References module, and the next lesson in this module is about "How Do Pointer Arithmetic and Arrays Interact?".
Addresses and the address-of operator
Every variable lives somewhere in the memory, and the compiler gives it an address. The ampersand operator retrieves that address.
#include <iostream>
int main() {
int track_count = 12;
int* pointer_to_count = &track_count;
std::cout << "value: " << track_count << '\n';
std::cout << "address: " << &track_count << '\n';
std::cout << "through the pointer: " << *pointer_to_count << '\n';
return 0;
}Read the three lines like this. The value of track_count is 12. The address of track_count is some number that the operating system chose. And dereferencing the pointer gives 12 back, because the pointer points at that variable.
The dereference operator
The asterisk is the inverse of the ampersand. Where &x gives you the address of x, *p gives you the object at the address that is stored in p. The two cancel out.
#include <iostream>
int main() {
double duration = 214.5;
double* duration_pointer = &duration;
*duration_pointer = 180.0; // write through the pointer
std::cout << "duration: " << duration << '\n';
std::cout << "through pointer: " << *duration_pointer << '\n';
*duration_pointer += 20.0; // read, modify, write back
std::cout << "after adding: " << duration << '\n';
return 0;
}The output confirms that writing through the pointer changed the original variable.
duration: 180
through pointer: 180
after adding: 200Declaring pointers
The asterisk goes next to the type name, which tells you that the pointer points at something of that type.
#include <iostream>
int main() {
int number = 42;
int* int_pointer = &number; // pointer to an int
double* double_pointer = nullptr; // pointer to a double, currently empty
std::cout << "number: " << *int_pointer << '\n';
*int_pointer = 7;
std::cout << "after write: " << number << '\n';
if (double_pointer == nullptr) {
std::cout << "double pointer is empty\n";
}
return 0;
}A pointer of the type int* can only point at an int. If you try to point an int* at a double, then the compiler refuses. That type checking is one of the main reasons that pointers are safe enough to use at all.
Pointers and arrays are closely related
An array name in most expressions behaves like a pointer to its first element. That is why indexing an array and dereferencing a pointer look the same.
#include <iostream>
int main() {
int ratings[3] = {4, 5, 3};
int* first = ratings;
std::cout << "ratings[0]: " << ratings[0] << '\n';
std::cout << "*first: " << *first << '\n';
std::cout << "same?: " << (first == &ratings[0]) << '\n';
first = &ratings[2];
std::cout << "after move: " << *first << '\n';
return 0;
}The output shows that the two forms are interchangeable.
ratings[0]: 4
*first: 4
same?: 1
after move: 3Pointers to pointers
A pointer is an object, so it can be pointed at. A pointer to a pointer is how you pass a pointer to a function, so that the function can change which object the original pointer refers to.
#include <iostream>
void swap_pointers(int*& first, int*& second) {
int* temporary = first;
first = second;
second = temporary;
}
int main() {
int a = 4;
int b = 5;
int* first = &a;
int* second = &b;
std::cout << "before: " << *first << " and " << *second << '\n';
swap_pointers(first, second);
std::cout << "after: " << *first << " and " << *second << '\n';
return 0;
}Notice the int*& in the parameter. It is a reference to a pointer. The output shows that the swap worked.
before: 4 and 5
after: 5 and 4Without the ampersand, the function would only be able to change its own copy of the pointer.
What pointers are for
Pointers earn their keep in three situations. The first one is dynamic memory, where the size of an object is not known until run time. The second one is linked structures, where each element points at the next one, and a playlist is the classic example. The third one is optional parameters, where nullptr means that no value was supplied.
Here is the beginning of a linked playlist. Each track holds its duration and a pointer to the next track.
#include <iostream>
#include <string>
struct Track {
std::string title;
int seconds;
Track* next;
};
int main() {
Track second = {"Blue Skies", 187, nullptr};
Track first = {"Slow Tide", 243, &second};
for (Track* current = &first; current != nullptr; current = current->next) {
std::cout << current->title << " (" << current->seconds << "s)\n";
}
return 0;
}The arrow operator is shorthand for dereferencing and then selecting a member, so current->next means (*current).next.
Pointers to const and const pointers
The const qualifier combines with pointers in two different ways, and the position matters.
#include <iostream>
int main() {
int value = 42;
const int* read_only = &value; // pointer to a const int
int* const fixed = &value; // a const pointer to an int
std::cout << "value: " << *read_only << '\n';
std::cout << "value: " << *fixed << '\n';
*fixed = 99; // allowed: the pointer is fixed, the int is not
std::cout << "after write: " << value << '\n';
return 0;
}Reading the declarations out loud settles them. A const pointer to an int is a pointer that cannot be reseated but whose target can be modified. A pointer to a const int is a pointer that can be reseated but whose target cannot be modified.
The output shows the write through the fixed pointer.
value: 42
value: 42
after write: 99Quick reference
&xgives the address of x, and*pgives the object that the pointer p points at.- A pointer is declared with an asterisk next to the type, such as
int* p. - Writing through a pointer changes the original object.
- An array name behaves like a pointer to its first element in most expressions.
- A pointer to a pointer lets a function change which object a pointer refers to.
- Use the arrow operator to reach a member through a pointer.
- A pointer to const cannot change the target, and a const pointer cannot be reseated.
Try it yourself: write a program that stores three track durations in an array, and then write a small function that takes an int* and doubles every value in place. Call it with the array and print the results. Next, extend the linked playlist above to three tracks and confirm that the loop prints all three in order.