Introduction to Pointers

In this chapter, we'll learn about pointers in C++. Pointers are one of the most important, but also most feared concepts in C++. Don't worry, we'll master them together!

Imagine the following situation: You have a large data file (like a video) and you want to pass it to a function for processing. You have two options:

  1. Create a copy of the entire file and pass that to the function
  2. Pass the function only information about where the file is located in memory

The first option is like sending a friend an entire video through messenger. The second option is like sending them just a link to the video on YouTube. It's obvious that the second option is more efficient - and that's exactly what pointers are for!

A pointer is a variable that contains the address of another variable in the computer's memory. It's like GPS coordinates that point to a specific location. Let's look at a simple example:

#include <iostream>

int main() {
    int number = 42;          // Regular variable
    int* pointer = &number;   // Pointer to this variable

    std::cout << "Value of number: " << number << std::endl;
    std::cout << "Address of number: " << pointer << std::endl;
    std::cout << "Value at address: " << *pointer << std::endl;

    return 0;
}

This program creates a variable number with value 42 and a pointer pointer that points to this variable. The & symbol gets the address of the variable and the * operator allows us to access the value at the given address.

Pointers are the foundation for:

  • Efficient memory management
  • Dynamic memory allocation
  • Passing large data to functions
  • Creating complex data structures (e.g., linked lists)

In the following exercises, we'll learn to work with pointers and harness their power!

Instructions

Run the program and look at the output. Notice that the memory address doesn't tell us humans much. When you're ready, move on to the next exercise!

Start programming for free

By signing up, you agree to the Terms of Service and Privacy Policy.

Or sign up with:

1/5

Introduction to Pointers | Start Coder