๐ŸŽ“ A1Learner
๐Ÿ”

C++ Pointers

A pointer is a variable that holds the address of another variable. An address is the place in memory where a variable is stored.

Reading through a pointer

p holds the address of score. Printing *p prints the value stored at that address.

#include <iostream>
#include <vector>

int main() {
  int score = 80;
  int* p = &score;
  std::cout << *p << std::endl;
  return 0;
}

Writing through a pointer

The line *p = 95 writes 95 into the place p points at. That place is score, so score changes.

#include <iostream>
#include <vector>

int main() {
  int score = 80;
  int* p = &score;
  *p = 95;
  std::cout << score << std::endl;
  return 0;
}

Aiming a pointer at a new variable

p first points at first. Storing a new address then aims p at second.

#include <iostream>
#include <vector>

int main() {
  int first = 10;
  int second = 20;
  int* p = &first;
  std::cout << *p << std::endl;
  p = &second;
  std::cout << *p << std::endl;
  return 0;
}

Example

#include <iostream>
#include <vector>

int main() {
  int north = 15;
  int south = 30;
  int* p = &north;
  std::cout << "First: " << *p << std::endl;
  p = &south;
  std::cout << "Second: " << *p << std::endl;
  return 0;
}

Key points

  • A pointer is declared with * after the type.
  • The & sign before a variable gives its address.
  • Dereferencing means reading or writing the value at the address a pointer holds.
  • The * sign before a pointer name stands for the value it points at.
  • Writing through a dereferenced pointer changes the variable it points at.
  • A pointer can be aimed at a new variable by storing a new address in it.

In this example, the pointer starts by pointing at the first variable. It prints 15 through the pointer. The pointer then aims at the second variable and prints 30.

Note

An address is a number that changes each run, so this course never prints one.

Try it Yourself

Edit the code, then press Run.

Running is simulated ยท Programiz C++ Compiler

Exercise

What does *p give when p points at score?