Pointer basics in C++

Level 4201 keystrokes

Stores the address of a variable in a pointer, reads the value through it and changes the variable through the pointer.

C++ code

1int value = 42;
// &value takes the address of value; ptr now points to it
2int* ptr = &value;
3
// Print the value directly: 42
4cout << "Value: " << value << endl;
// Print the address held by ptr; it differs on every run
5cout << "Address: " << ptr << endl;
// *ptr dereferences the pointer and reads 42
6cout << "Via pointer: " << *ptr << endl;
7
// Write through the pointer: this changes value itself
8*ptr = 100;
// Print 100, proving value was changed via ptr
9cout << "New value: " << value << endl;

Output

Value: 42
Address: 0x7ffd...
Via pointer: 42
New value: 100
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.

  • <× 24
  • "× 8
  • ;× 7
  • :× 4
  • *× 3
  • =× 3
  • &× 1

More C++ examples at level 4

← C++ typing practice