Pointer basics in C++

Level 3118 keystrokes

& takes the address of x and * reads or writes the value at that address. Writing 20 through the pointer changes x. The printed address differs from run to run.

C++ code

1int x = 10;
// int* is a pointer to int; &x is the address of x
2int* ptr = &x;
// Prints 10
3cout << x << endl;
// Prints the address itself in hexadecimal; the value differs on every run
4cout << ptr << endl;
// *ptr dereferences the pointer and reads the value it points to: 10
5cout << *ptr << endl;
// Writes 20 to the address ptr holds, which is x
6*ptr = 20;
// x was changed through the pointer: prints 20
7cout << x << endl;

Output

10
0x7ffd123
10
20
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this C++ code and how often they appear.

  • <× 16
  • ;× 7
  • *× 3
  • =× 3
  • &× 1

More C++ examples at level 3

← C++ typing practice