C++:C++ Pointers and References: Memory Addresses Explained
C++•Pointers & References

C++ Pointers and References: Memory Addresses Explained

Pointers hold memory addresses directly, enabling manual memory manipulation, while references provide safe aliases.

Syntax

int* ptr = &val; int& ref = val; *ptr = 20;

Parameters & Values

Key components and acceptable values for this structure:

ParameterTypeDescription
&Address-of OperatorRetrieves the memory address of a variable.
*Dereference OperatorAccesses or mutates value stored at memory address.

Ready-to-Run Code Example

Executable in Compilra

Run this complete, working example directly without installing C++ locally:

#include <iostream>

int main() {
    int target = 42;
    int* ptr = &target;      // ptr stores memory address of target
    int& ref = target;       // ref is an alias for target

    std::cout << "Original Value:      " << target << "\n";
    std::cout << "Memory Address:      " << ptr << "\n";
    std::cout << "Dereferenced Value:  " << *ptr << "\n";

    // Mutate via pointer dereference
    *ptr = 100;
    std::cout << "\nAfter *ptr = 100:\n";
    std::cout << "  target: " << target << "\n";
    std::cout << "  ref:    " << ref << "\n";

    return 0;
}
Expected Output:
Original Value:      42
Memory Address:      [address]
Dereferenced Value:  42

After *ptr = 100:
  target: 100
  ref:    100

How It Works: Step-by-Step

  • Lines 5-6: Assigns address of target to pointer and binds reference alias.
  • Line 10: *ptr dereferences address to read stored integer.
  • Line 13: Writing to *ptr directly mutates target in memory.

Key Concepts

  • Pointers can be reassigned to point elsewhere and can be nullptr.
  • References cannot be null and cannot be reseated after initialization.
  • Dereferencing a nullptr or uninitialized pointer causes Segmentation Fault.

Common Mistake: Dereferencing a nullptr or uninitialized pointer

Accessing memory at an invalid address crashes the program with a segmentation fault.

❌ Incorrect
int* ptr = nullptr;
*ptr = 10; // Segmentation Fault (Crash)!
✅ Correct
int val = 0;
int* ptr = &val;
*ptr = 10; // Safe

Related C++ Tutorials & Compiler

Run and test C++ on Compilra

Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.

C++ Online Compiler