Search⌘ K
AI Features

Pointers

Explore the concept of pointers in C++ and how they provide direct access to memory addresses. Learn to declare and dereference pointers safely using nullptr, understand their connection to arrays, and master pointer arithmetic. This lesson teaches when and why to use pointers wisely for efficient data traversal and interaction with legacy code.

Up to this point, we have accessed variables exclusively by their names. If we wanted to change a value, we used the variable name. However, under the hood, the computer does not recognize these names; it only knows memory addresses where data is stored. To become proficient C++ engineers, we must learn to look past the variable names and interact directly with this memory.

We use pointers to achieve this. Pointers give us direct access to the memory map, enabling efficient data traversal and hardware-level control. This is one of the most powerful features of C++, but it requires discipline. Managing memory manually is powerful, but it comes with the responsibility to be precise. In this lesson, we will demystify what a pointer is, its relationship to the arrays we have just learned, and how to use it safely in modern C++.

Declaring pointers

A pointer is simply a variable that stores a memory address. To declare a pointer type variable, we add an asterisk (*) to any type. For example, just as an int stores a number, the int* stores the location where that int variable is stored.

C++ 23
#include <iostream>
int main() {
int number = 42;
// Declare a pointer 'ptr' and assign it the address of 'number'
int* ptr = &number;
std::cout << "Original Value: " << number << "\n";
std::cout << "Pointer holds address: " << ptr << "\n";
}

Let’s understand this step by step:

  • Line 7: We declare int* ptr. This variable ptr now holds the address of number.

  • Line 9-10: We print the ptr address and the original value. ... ... ...