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

A pointer in C++ is a variable holding the raw memory address of another object. Pointers are declared using the asterisk (*) syntax, assigned addresses via the address-of operator (&), and accessed using the dereference operator (*). Modern C++ replaces raw pointers for ownership with smart pointers (std::unique_ptr, std::shared_ptr) and uses nullptr instead of NULL/0.

Detailed Explanation & Mechanics

1. Pointer Architecture & Dereferencing:

Architecture Diagram
POINTER MEMORY MODEL:
Variable 'val' (Address: 0x7ffd10) ──> [ Value: 42 ]
Pointer  'ptr' (Address: 0x7ffd20) ──> [ Stores: 0x7ffd10 ]
*ptr ──> Accesses value 42 at address 0x7ffd10

2. The `nullptr` Keyword (C++11):

nullptr has type std::nullptr_t, eliminating ambiguous overloads where NULL (macro for 0) could mistakenly bind to integer parameters instead of pointer overloads.

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.
We value your privacy & transparency

OperateTools uses cookies and local storage to ensure basic tool functionality, preserve preferences, and analyze aggregated traffic. We never sell your personal data or index your document files. Learn more in our Privacy Policy.