Back to C++
2026-02-116 min read

C++ Pointers

Learn C++ Pointers step by step with clear examples and exercises.

Title: Mastering C++ Pointers: A full guide for Every Programmer

Why This Matters

C++ pointers are an essential tool that allows you to manipulate memory directly, enabling dynamic memory allocation, more complex programming tasks, and optimizing code performance. Understanding pointers is crucial for advanced C++ programming, interview preparation, and debugging real-world issues.

Prerequisites

Before diving into C++ pointers, it's essential to have a solid foundation in the following topics:

  1. Basic C++ syntax and control structures (if, loops)
  2. Data types and variables
  3. Functions and function overloading
  4. Arrays and strings
  5. Classes and objects
  6. Understanding memory management concepts like stack and heap.
  7. Familiarity with the Standard Template Library (STL), particularly vectors and iterators.
  8. Adequate understanding of operator precedence and overloading.
  9. Knowledge of exception handling in C++.
  10. Familiarity with basic data structures such as linked lists, stacks, queues, and trees.

Core Concept

A pointer is a variable that stores the memory address of another variable. In C++, pointers are declared using the * symbol. Here's a simple example:

int num = 10;
int *ptr = # // ptr now holds the memory address of num

To access the value stored at the address pointed to by a pointer, you use the dereference operator *. For instance:

std::cout << *ptr; // Outputs 10, as ptr points to num

Pointer Types

C++ supports different types of pointers, including:

  • Basic data type pointers: int, char, double*, etc.
  • Array pointers: int*, which can be used to manipulate entire arrays.
  • Pointer to a pointer: int (double asterisk), useful for multi-dimensional arrays and recursive functions.
  • Smart pointers: unique_ptr, shared_ptr, and weak_ptr, which help manage memory automatically in modern C++.

Pointer Arithmetic

You can perform arithmetic operations on pointers to move through memory. For instance:

int arr[] = {1, 2, 3};
int *p = &arr[0]; // p points to the first element of arr

// Move p to the second element (increment by sizeof(int))
++p;
std::cout << *p; // Outputs 2

Pointer Dereferencing and Assignment

You can assign values to pointers, as well as dereference them:

int num = 10;
int *ptr = &num;
*ptr = 20; // Changes the value of num to 20
std::cout << num; // Outputs 20

Pointer Constants and References

  • Constant pointers: const int *ptr prevents you from modifying the data pointed to by the pointer.
  • Pointer to constant: int const *ptr prevents you from changing the pointer's value, but allows modification of the data it points to.
  • Const references: int &ref creates a reference that cannot be reassigned, but can modify the original variable.

Worked Example

Let's create a simple program that dynamically allocates memory for an array and fills it with user input:

#include <iostream>
using namespace std;

int main() {
int *arr; // Declare a pointer to an integer array
int size; // Size of the array

cout << "Enter the size of the array: ";
cin >> size;

arr = new int[size]; // Dynamically allocate memory for the array

cout << "Enter " << size << " elements:" << endl;
for (int i = 0; i < size; ++i) {
cin >> arr[i];
}

cout << "The entered array is:" << endl;
for (int i = 0; i < size; ++i) {
cout << arr[i] << " ";
}

delete[] arr; // Deallocate the memory after use
return 0;
}

In this example, we dynamically allocate memory for an array of integers using new, input user values into the array, and then display the entered array before deallocating the memory with delete[].

Common Mistakes

  1. Forgetting to initialize pointers: Always initialize your pointers to nullptr or an appropriate default value before using them.
  2. Accessing invalid memory: Make sure you don't dereference a null pointer or go out of bounds when using pointers.
  3. Incorrect pointer arithmetic: Remember that incrementing a pointer by 1 moves it to the next element of its data type, not just one byte.
  4. Not deallocating memory: Always free up dynamically allocated memory after use to avoid memory leaks.
  5. Confusing pointers and references: References are constants bound to variables, while pointers store memory addresses.
  6. Using raw pointers instead of smart pointers: Smart pointers help manage memory automatically, reducing the risk of memory leaks and resource management errors.
  7. Not understanding scope rules: Be aware that local variables go out of scope when they are no longer in their enclosing block, which can lead to undefined behavior if you still have a pointer pointing to them.
  8. Misusing operator overloading: Ensure that your operator overloading does not violate the principles of encapsulation and abstraction.
  9. Ignoring exception handling: Use try-catch blocks to handle exceptions gracefully in case of errors during runtime.
  10. Not properly managing dynamic memory: Be cautious when using new and delete, as they can lead to memory fragmentation if not managed correctly.

Practice Questions

Question 1:

Given the following code snippet, what is the output of the program?

int arr[] = {1, 2, 3};
int *p = &arr[0];
std::cout << *(p + 1);

Answer:

The output will be 2, as we are moving one step ahead of the starting address of the array.

Question 2:

What is the purpose of using a smart pointer in C++?

Answer:

Smart pointers help manage memory automatically, reducing the risk of memory leaks and resource management errors by taking care of tasks like deleting objects when they are no longer needed or sharing ownership between multiple pointers.

FAQ

What is a pointer in C++?

A pointer in C++ is a variable that stores the memory address of another variable.

How do I initialize a pointer in C++?

You can initialize a pointer by assigning it the address of an existing variable, or setting it to nullptr for uninitialized pointers.

What is the difference between a pointer and a reference in C++?

A pointer stores a memory address, while a reference is an alias for another variable. References cannot be reassigned, but pointers can.

How do I dynamically allocate memory using new in C++?

You can dynamically allocate memory using new followed by the data type of the memory you want to allocate. For example: int *arr = new int[10]; allocates an array of 10 integers on the heap.

How do I deallocate dynamically allocated memory in C++?

You can deallocate dynamically allocated memory using delete[] for arrays and delete for individual objects. For example: delete[] arr; deallocates an array of integers previously allocated with new.

What are smart pointers in C++, and why should I use them?

Smart pointers are classes that manage the lifetime of dynamically allocated memory automatically, reducing the risk of memory leaks and resource management errors. Examples include unique_ptr, shared_ptr, and weak_ptr.

What is a null pointer in C++?

A null pointer (nullptr) is a special value used to indicate that a pointer does not point to any valid memory location.

How do I check if a pointer is null in C++?

You can check if a pointer is null by comparing it with nullptr. For example: if (ptr == nullptr) { /* handle null pointer */ }

What happens when I access invalid memory using a pointer in C++?

Accessing invalid memory using a pointer can lead to undefined behavior, including segmentation faults and memory corruption.

How do I avoid memory leaks when using pointers in C++?

Avoid memory leaks by always deallocating dynamically allocated memory after use, properly managing dynamic memory with smart pointers, and being mindful of the scope of your variables.

C++ Pointers | C++ | XQA Learn