Understanding Reference and Pointer Types

Pointer to Pointer Use Cases

In what situations would I need to use a pointer to a pointer in C++?

Abstract art representing computer programming

While pointers to pointers (i.e., int**) can be confusing and are often a sign of complex code, there are some situations where they are necessary or useful:

  1. When you need to modify a pointer in a function. If you want a function to be able to modify a pointer passed to it, you need to pass a pointer to that pointer.
  2. When working with multidimensional arrays. A 2D array is essentially an array of arrays, so a pointer to a 2D array is a pointer to a pointer.
  3. When implementing complex data structures like linked lists or trees, where each node contains a pointer to another node.

Here's an example of a function that modifies a pointer:

#include <iostream>

void AllocateInt(int** ptr) {
  *ptr = new int;  // Allocate memory
  **ptr = 10;      // Set value
}

int main() {
  int* p = nullptr;
  AllocateInt(&p);  // Pass pointer to pointer

  std::cout << "*p = " << *p << "\n";

  delete p;  // Deallocate memory
}
*p = 10

In this case, AllocateInt needs to modify the pointer p itself (not just the value it points to), so we need to pass a pointer to p, which is a pointer to a pointer.

However, pointers to pointers can quickly make code harder to understand and maintain, so they should be used judiciously. Often, there are better alternatives like references, smart pointers, or higher-level abstractions.

Answers to questions are automatically generated and may not have been reviewed.

A computer programmer
Part of the course:

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Free, unlimited access

This course includes:

  • 125 Lessons
  • 550+ Code Samples
  • 96% Positive Reviews
  • Regularly Updated
  • Help and FAQ
Free, Unlimited Access

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Screenshot from Warhammer: Total War
Screenshot from Tomb Raider
Screenshot from Jedi: Fallen Order
Contact|Privacy Policy|Terms of Use
Copyright © 2024 - All Rights Reserved