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:
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.
Learn the fundamentals of references, pointers, and the const
keyword in C++ programming.