Topic 28 of 91 5. C++ Pointers and References Interactive Tutorial

Pointers in C++: Memory Addresses, Dereferencing, and Practical Uses

16 mins read Last updated: 26 Sep 2026 24,500 views

Direct Answer & Core Concept

Pointers are one of the most important concepts in C++. They allow a program to work directly with memory addresses and access data stored at those locations.

Pointers are useful for working with arrays, dynamic memory allocation, functions, data structures, and efficient memory management.

Detailed Explanation & Mechanics

1. What Is a Pointer in C++?

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

Normally, a variable stores a value. A pointer stores the address where that value is located in memory.

For example:

main.cpp
Run Online
#include <iostream>
using namespace std;

int main() {
    int number = 25;

    int* ptr = &number;

    cout << "Value: " << number << endl;
    cout << "Address: " << &number << endl;
    cout << "Pointer value: " << ptr << endl;
    cout << "Value through pointer: " << *ptr << endl;

    return 0;
}

Example output:

main.cpp
Run Online
Value: 25
Address: 0x7ffe1234
Pointer value: 0x7ffe1234
Value through pointer: 25

The memory address shown above is illustrative. Actual addresses differ between program executions and systems.

Explanation

  • number stores the integer value 25.

  • &number obtains the memory address of number.

  • ptr stores that address.

  • *ptr accesses the value stored at that address.

A pointer provides indirect access to another variable.

2. Pointer Declaration in C++

To declare a pointer, specify the data type followed by an asterisk (*) and the pointer variable name.

Syntax

Examples

main.cpp
Run Online
int* intPtr;
float* floatPtr;
double* doublePtr;
char* charPtr;

Each pointer has a type that determines the type of object it can point to.

For example:

main.cpp
Run Online
int number = 100;
int* ptr = &number;

Here, ptr is an integer pointer because it points to an integer variable.

Different pointer declaration styles

All the following declarations are valid:

main.cpp
Run Online
int* ptr1;
int *ptr2;
int * ptr3;

They have the same meaning. A common style is int* ptr.

Important: When declaring multiple pointers, remember that the asterisk belongs to each declarator.

Here, first is a pointer, but second is a normal integer.

To declare two pointers:

3. Understanding the Address-of Operator (&)

The address-of operator (&) returns the memory address of a variable.

Example

main.cpp
Run Online
#include <iostream>
using namespace std;

int main() {
    int age = 30;

    cout << "Age: " << age << endl;
    cout << "Memory address: " << &age << endl;

    return 0;
}

Example output:

main.cpp
Run Online
Age: 30
Memory address: 0x7ffe1234

The address is not fixed. It can change when the program runs again.

Using the address operator with a pointer

main.cpp
Run Online
int age = 30;
int* ptr = &age;

The expression &age gets the address of age, and that address is stored in ptr.

4. Understanding the Dereference Operator (*)

The dereference operator (*) accesses the value stored at the memory address held by a pointer.

This operation is also called indirection.

Example

main.cpp
Run Online
#include <iostream>
using namespace std;

int main() {
    int number = 50;

    int* ptr = &number;

    cout << *ptr << endl;

    return 0;
}

Output:

Changing a variable through a pointer

You can also modify the original variable by dereferencing its pointer.

main.cpp
Run Online
#include <iostream>
using namespace std;

int main() {
    int number = 50;

    int* ptr = &number;

    *ptr = 100;

    cout << "Number: " << number << endl;

    return 0;
}

Output:

The statement *ptr = 100 changes the value of the variable whose address is stored in ptr.

Difference between & and *

OperatorMeaningExample
&Gets a variable's address&number
*Declares a pointer or dereferences oneint* ptr, *ptr

5. How to Initialize a Pointer

A pointer should be initialized before it is dereferenced.

Example

main.cpp
Run Online
#include <iostream>
using namespace std;

int main() {
    int value = 75;

    int* ptr = &value;

    cout << *ptr << endl;

    return 0;
}

Output:

Uninitialized pointer

main.cpp
Run Online
int* ptr;

// Do not dereference ptr here.

An uninitialized pointer contains an indeterminate value. Dereferencing it can cause undefined behavior.

A safer option is to initialize a pointer to nullptr when it does not yet point to an object.

6. Null Pointers in C++

A null pointer does not point to a valid object or function.

C++ provides the nullptr keyword to represent a null pointer.

Example

main.cpp
Run Online
#include <iostream>
using namespace std;

int main() {
    int* ptr = nullptr;

    if (ptr == nullptr) {
        cout << "Pointer is null" << endl;
    }

    return 0;
}

Output:

Why use nullptr?

  • It makes the pointer's empty state clear.

  • It helps prevent accidental use of uninitialized pointer values.

  • It can be checked before accessing an object.

  • It is safer and clearer than using the integer literal 0.

Important: Never dereference a null pointer.

7. Pointer Arithmetic in C++

Pointer arithmetic allows certain operations on pointers, such as moving to the next or previous element of an array.

When a pointer is incremented, it advances by the size of the type it points to, not necessarily by one byte.

Example: Incrementing a pointer

main.cpp
Run Online
#include <iostream>
using namespace std;

int main() {
    int numbers[] = {10, 20, 30, 40};

    int* ptr = numbers;

    cout << *ptr << endl;

    ptr++;

    cout << *ptr << endl;

    return 0;
}

Output:

The pointer initially points to the first array element. After ptr++, it points to the next element.

Common pointer arithmetic operations

OperationMeaning
ptr++Moves to the next element
ptr--Moves to the previous element
ptr + nMoves forward by n elements
ptr - nMoves backward by n elements
ptr1 - ptr2Calculates the element distance between pointers into the same array

Pointer arithmetic is only valid within the same array object or one position past its last element. The one-past position must not be dereferenced.

8. Pointers and Arrays

Pointers and arrays are closely related in C++.

In many expressions, an array name converts to a pointer to its first element. This is called array-to-pointer conversion.

Example

main.cpp
Run Online
#include <iostream>
using namespace std;

int main() {
    int numbers[] = {10, 20, 30, 40, 50};

    int* ptr = numbers;

    for (int i = 0; i < 5; i++) {
        cout << *(ptr + i) << endl;
    }

    return 0;
}

Output:

Explanation

  • numbers converts to a pointer to its first element in this assignment.

  • ptr points to numbers[0].

  • ptr + i points to the element at index i.

  • *(ptr + i) reads that element.

For an array, these expressions access the same element:

Important: An array and a pointer are not the same thing. An array has its own fixed size and storage, while a pointer is a separate variable that stores an address.

9. Pointer to Pointer in C++

A pointer to pointer stores the address of another pointer.

It is also called a double pointer.

Syntax

Example

main.cpp
Run Online
#include <iostream>
using namespace std;

int main() {
    int number = 100;

    int* ptr = &number;

    int** doublePtr = &ptr;

    cout << "Value: " << number << endl;
    cout << "Using pointer: " << *ptr << endl;
    cout << "Using double pointer: " << **doublePtr << endl;

    return 0;
}

Output:

main.cpp
Run Online
Value: 100
Using pointer: 100
Using double pointer: 100

How does it work?

  • number stores 100.

  • ptr stores the address of number.

  • doublePtr stores the address of ptr.

  • **doublePtr accesses the original integer value.

Double pointers are useful in certain dynamic data structures and when a function needs to modify a pointer variable itself.

10. Pointers and Functions

Pointers can be passed to functions to allow a function to access or modify the original variable.

Example: Passing a pointer to a function

main.cpp
Run Online
#include <iostream>
using namespace std;

void updateValue(int* ptr) {
    if (ptr != nullptr) {
        *ptr = 500;
    }
}

int main() {
    int number = 100;

    updateValue(&number);

    cout << number << endl;

    return 0;
}

Output:

Explanation

  • &number passes the address of the original variable.

  • int* ptr receives that address.

  • *ptr = 500 modifies the original variable.

  • The updated value is visible in main().

For many ordinary C++ functions, references are simpler and safer when you only need to modify an existing object. Pointers are useful when an optional object or explicit address-based behavior is needed.

11. Dynamic Memory Allocation Using Pointers

C++ allows memory to be allocated dynamically while a program is running.

The new operator allocates memory, and delete releases memory allocated with new.

Example: Using new and delete

main.cpp
Run Online
#include <iostream>
using namespace std;

int main() {
    int* ptr = new int;

    *ptr = 200;

    cout << "Value: " << *ptr << endl;

    delete ptr;
    ptr = nullptr;

    return 0;
}

Output:

Explanation

  1. new int allocates memory for one integer.

  2. The returned address is stored in ptr.

  3. *ptr = 200 stores a value in the allocated memory.

  4. delete ptr releases that memory.

  5. ptr = nullptr prevents the pointer from retaining a stale address.

Dynamic array allocation

You can also allocate an array dynamically.

main.cpp
Run Online
#include <iostream>
using namespace std;

int main() {
    int size = 3;

    int* numbers = new int[size]{10, 20, 30};

    for (int i = 0; i < size; i++) {
        cout << numbers[i] << endl;
    }

    delete[] numbers;
    numbers = nullptr;

    return 0;
}

Output:

Use delete[] for memory allocated with new[]. Using the wrong form of delete results in undefined behavior.

Modern C++ recommendation

In modern C++, prefer standard library containers such as std::vector for dynamic arrays and smart pointers such as std::unique_ptr or std::shared_ptr for managed dynamic objects.

These tools help reduce memory leaks and ownership errors.

12. Constant Pointers and Pointers to Constants

C++ provides different ways to use const with pointers.

Pointer to a constant value

You cannot modify the pointed-to value through this pointer, but you can make the pointer point somewhere else.

Constant pointer

The pointer cannot be made to point to another address, but the pointed-to value can be modified through it.

Constant pointer to a constant value

main.cpp
Run Online
const int* const ptr = &number;

Neither the pointer nor the pointed-to value can be modified through this pointer.

Comparison

DeclarationChange pointer address?Modify value through pointer?
int* ptrYesYes
const int* ptrYesNo
int* const ptrNoYes
const int* const ptrNoNo

13. Void Pointers in C++

A void* is a pointer type that can hold the address of an object of any object type.

However, a void* cannot be directly dereferenced because it does not specify the pointed-to type.

Example

main.cpp
Run Online
#include <iostream>
using namespace std;

int main() {
    int number = 100;

    void* ptr = &number;

    cout << *static_cast<int*>(ptr) << endl;

    return 0;
}

Output:

Here, static_cast<int*>(ptr) converts the void* back to an int* before dereferencing it.

The cast must match the actual object type. A void* is not a replacement for type-safe pointers in ordinary C++ code.

14. Function Pointers in C++

A function pointer stores the address of a function. It allows a function to be called indirectly through a pointer.

Syntax

main.cpp
Run Online
return_type (*pointer_name)(parameter_types);

Example

main.cpp
Run Online
#include <iostream>
using namespace std;

int add(int a, int b) {
    return a + b;
}

int main() {
    int (*operation)(int, int) = add;

    cout << operation(10, 20) << endl;

    return 0;
}

Output:

Explanation

  • add() is a function that accepts two integers.

  • operation is a pointer to a function with a matching signature.

  • operation(10, 20) calls the function through the pointer.

Function pointers are useful for callbacks, selecting operations, and working with some C and C++ APIs.

15. Practical Uses of Pointers in C++

Pointers are used in many areas of C++ programming.

Use caseHow pointers help
Dynamic memoryManage objects created during program execution
ArraysAccess and process array elements
FunctionsPass addresses and modify original objects
Linked listsConnect nodes in a data structure
TreesLink parent and child nodes
PolymorphismUse base-class pointers to access derived objects
Function callbacksCall functions indirectly
System programmingWork with memory and low-level interfaces

Example: Using pointers in a linked-list node

main.cpp
Run Online
#include <iostream>
using namespace std;

struct Node {
    int data;
    Node* next;
};

int main() {
    Node first{10, nullptr};
    Node second{20, nullptr};

    first.next = &second;

    cout << first.data << endl;
    cout << first.next->data << endl;

    return 0;
}

Output:

The next pointer connects the first node to the second node. This is a basic example of how pointers are used to build linked lists.

16. Common Pointer Errors in C++

Pointers are powerful, but incorrect pointer usage can cause serious programming errors.

1. Uninitialized pointer

main.cpp
Run Online
int* ptr;

// Dangerous: ptr does not point to a known object.

Solution:

2. Dereferencing a null pointer

main.cpp
Run Online
int* ptr = nullptr;

// Dangerous: *ptr = 10;

Solution: Check whether a pointer is non-null before dereferencing it.

3. Dangling pointer

A dangling pointer refers to an object whose lifetime has ended.

For example, returning the address of a local variable from a function creates a dangling pointer.

Solution: Do not use pointers after the pointed-to object's lifetime ends. Use appropriate ownership tools.

4. Memory leak

A memory leak occurs when dynamically allocated memory is not released and no longer has a usable owner.

Solution: Prefer RAII and smart pointers, or ensure every allocation is correctly released.

5. Double deletion

Deleting the same dynamically allocated object more than once causes undefined behavior.

Solution: Use clear ownership rules and prefer smart pointers.

6. Accessing memory outside an array

Pointer arithmetic beyond an array's valid range can cause undefined behavior.

Solution: Keep pointer operations within the array or its one-past position, and never dereference the one-past pointer.

17. Pointers vs References in C++

Pointers and references both allow indirect access to objects, but they have different properties.

FeaturePointerReference
DeclarationUses *Uses &
InitializationCan be initialized laterMust be initialized when declared
Null stateCan be nullptrCannot be a null reference in normal valid use
ReassignmentCan point to another objectCannot be reseated to another object
AccessUses * to dereferenceUsed like the original variable
ArithmeticSupported for suitable pointersNot supported
Typical useOptional objects and address-based operationsRequired object parameters and aliases

Example using a reference

main.cpp
Run Online
#include <iostream>
using namespace std;

void update(int& value) {
    value = 500;
}

int main() {
    int number = 100;

    update(number);

    cout << number << endl;

    return 0;
}

Output:

References are often a simpler choice when a function requires an existing object. Pointers are appropriate when the address itself or an optional object matters.

18. Best Practices for Using Pointers

Follow these practices when writing pointer-based C++ programs:

  1. Initialize pointers before using them.

  2. Use nullptr to represent an empty pointer.

  3. Never dereference a null, dangling, or otherwise invalid pointer.

  4. Avoid unnecessary manual memory allocation.

  5. Prefer std::vector for dynamic arrays.

  6. Prefer std::unique_ptr for exclusive dynamic ownership.

  7. Use std::shared_ptr only when shared ownership is genuinely required.

  8. Match new with delete and new[] with delete[].

  9. Avoid returning pointers to local variables.

  10. Keep pointer ownership and object lifetimes clear.

19. Frequently Asked Questions (FAQs)

Q1. What is a pointer in C++?

A pointer is a variable that stores the memory address of another object or function.

Q2. What is the use of a pointer?

Pointers are used for dynamic memory management, arrays, functions, linked lists, trees, polymorphism, and low-level programming.

Q3. What does the * operator mean in C++?

The * operator is used to declare a pointer and to dereference a pointer to access the object it points to.

Q4. What does the & operator mean in C++?

The & operator obtains the address of an object. It is also used in reference declarations, depending on its context.

Q5. What is a null pointer?

A null pointer does not point to a valid object or function. In modern C++, use nullptr to represent one.

Q6. What is pointer arithmetic?

Pointer arithmetic is the process of moving a pointer between elements of the same array, using operations such as ptr++ and ptr + n.

Q7. What is a double pointer?

A double pointer is a pointer that stores the address of another pointer. It is declared using two asterisks, such as int** ptr.

Q8. What is dynamic memory allocation?

Dynamic memory allocation allows a program to request memory during execution. C++ provides new and delete, while modern C++ also offers containers and smart pointers.

Q9. What is a dangling pointer?

A dangling pointer refers to an object whose lifetime has ended or whose storage is no longer valid for access.

Q10. Are pointers and arrays the same in C++?

No. Array names convert to pointers in many expressions, but arrays and pointers are different types with different properties.

Runnable Code Example: Pointers in C++

C++20 / C++23
main.cpp
Run Online
#include <iostream>

void modifyViaPointer(int* ptr) {
    if (ptr != nullptr) {
        *ptr = 999; // Dereference and write
    }
}

int main() {
    int sensorData = 100;
    int* ptr = &sensorData; // Store address

    std::cout << "Original Value: " << sensorData << "
";
    std::cout << "Memory Address: " << ptr << "
";
    std::cout << "Dereferenced:   " << *ptr << "
";

    modifyViaPointer(ptr);
    std::cout << "After modification: " << sensorData << "
";
    return 0;
}

Common C++ Technical Interview Questions & Answers

Interview Prep
Q

Q: Why is nullptr superior to NULL in C++?

A: `NULL` is an integer macro (`0` or `0L`), causing overload resolution ambiguities between `f(int)` and `f(int*)`. `nullptr` is a distinct keyword with type `std::nullptr_t` that safely converts only to pointer types.
Q

Q: What is a dangling pointer?

A: A pointer that still holds the memory address of an object that has already been deallocated or gone out of scope. Dereferencing a dangling pointer produces undefined behavior / memory corruption.

Key Takeaways, Modern Best Practices & Idioms

C++ Best Practices & Production Rules

1. Always initialize pointers to nullptr or a valid memory address immediately.
2. Check pointers for nullptr before dereferencing.
3. Use smart pointers (std::unique_ptr) to eliminate raw ownership pointers.