Memory and pointers · Lesson 11 of 21
Pointers
Addresses, * and &, nullptr, and pointers with arrays.
11 minutes3 games
Every variable lives somewhere in memory, and that place has an address (a number). A pointer is a variable whose value is another variable's address: it "points" at it.
&xmeans "the address of x".int* pmeans "p points to an int".*pmeans "the value p points to" (a dereference).
C++
#include <iostream>
int main() {
int xp = 100;
int* p = &xp; // p holds xp's address
std::cout << "xp = " << xp << "\n";
std::cout << "*p = " << *p << "\n";
std::cout << "same address? " << (p == &xp) << "\n";
*p = 250; // change xp through the pointer
std::cout << "xp is now " << xp << "\n";
int* nothing = nullptr;
if (nothing == nullptr) std::cout << "nothing points nowhere\n";
return 0;
}xp250int · at 0x7ffd10
p0x7ffd10int* → xp
nothingnullptrint* → (nothing)
p holds xp's address, so *p = 250 changed xp itself. (The real address changes every run.)
Step by step1 / 6
- ▶int a = 5;
- 2int b = 9;
- 3int* p = &a;
- 4*p = *p + 1;
- 5p = &b;
- 6*p = 0;
Variables
| a | 5 |
Output
…
A pointer can change what it points at.
Pointers and arrays
C++
#include <iostream>
int main() {
int scores[4] = {90, 75, 88, 60};
int* p = scores; // an array name turns into a pointer to its first element
std::cout << *p << " " << *(p + 2) << " " << p[3] << "\n";
for (int* it = scores; it != scores + 4; ++it) {
std::cout << *it << " ";
}
std::cout << "\n";
return 0;
}What's the output?
#include <iostream>
int main() {
int x = 3, y = 7;
int* p = &x;
int* q = &y;
*p = *q;
p = q;
*p = 1;
std::cout << x << " " << y << "\n";
}What will this code print?
Spot the bug
This function returns a pointer to something that's gone. Which line is the problem?
Exercise
Write void swapPtr(int* a, int* b) that swaps the two values through the pointers. The program must print 9 4.
Expected output: 9 4
C++
#include <iostream>
void swapPtr(int* a, int* b) {
}
int main() {
int x = 4, y = 9;
swapPtr(&x, &y);
std::cout << x << " " << y << "\n";
return 0;
}Learn more from
Played 0 of 3 games
Sign in to save your progress and earn XP.